-
2018-06-22 07:34:48
fun main(args: Array<String>) { val arrays = (0..10) var arrays1 = (2..8) /** * 获得基数 */ arrays.filter { it % 2 == 1 }.forEach(::println) /** * takeWhile只获取满足条件之前的数据 */ arrays1.takeWhile { it % 2 == 0 }.forEach(::println) }
@Pojos data class WorlderCup(val name: String, val old: Int, val host: String) { fun getTeamCount() { println("${name}参赛队伍一共32支") } } fun main(args: Array<String>) { /** * 使用let正对于某个对象进行操作 * 返回=》WorlderCup(name=俄罗斯世界杯, old=84, host=俄罗斯) */ worldercup().let { println(it) } //返回=>10000 100.let { println(it * 100) } /** * apply相当于this * 返回=>俄罗斯世界杯参赛队伍一共32支 */ worldercup().apply { getTeamCount() } /** * with把对象和this合并到一起 */ with(worldercup(), { println(name) }) /** * 使用with函数返回=》阿根廷不要为我哭泣 */ var bufferread = BufferedReader(FileReader("worldcup.txt")) with(bufferread) { var line: String while (true) { line = readLine() ?: break print(line) } close() } /** * 读取BuffererReader */ // println(bufferread.readText()) /** * 返回的对象有closeable方法的话 调用use 就不用手动调用close方法 */ BufferedReader(FileReader("worldcup.txt")).use { var line: String while (true) { line = it.readLine() ?: break print(line) } } } fun worldercup(): WorlderCup { return WorlderCup("俄罗斯世界杯", 84, "俄罗斯") }
更多相关内容 -
Kotlin use函数的魔法
2018-03-30 20:34:49原文地址:http://qjm253.cn/2018/03/30/kotlin_01/ 魔法预览实现了Closeable接口的对象...Kotlin的File对象和IO流操作变得行云流水 use函数的原型 /** * Executes the given [block] function on this resource and原文地址:https://blog.qjm253.cn/?p=391
魔法预览
- 实现了Closeable接口的对象可调用use函数
- use函数会自动关闭调用者(无论中间是否出现异常)
- Kotlin的File对象和IO流操作变得行云流水
use函数的原型
/** * Executes the given [block] function on this resource and then closes it down correctly whether an exception * is thrown or not. * * @param block a function to process this [Closeable] resource. * @return the result of [block] function invoked on this resource. */ @InlineOnly @RequireKotlin("1.2", versionKind = RequireKotlinVersionKind.COMPILER_VERSION, message = "Requires newer compiler version to be inlined correctly.") public inline fun <T : Closeable?, R> T.use(block: (T) -> R): R { var exception: Throwable? = null try { return block(this) } catch (e: Throwable) { exception = e throw e } finally { when { apiVersionIsAtLeast(1, 1, 0) -> this.closeFinally(exception) this == null -> {} exception == null -> close() else -> try { close() } catch (closeException: Throwable) { // cause.addSuppressed(closeException) // ignored here } } } }
- 可以看出,use函数内部实现也是通过try-catch-finally块捕捉的方式,所以不用担心会有异常抛出导致程序退出
- close操作在finally里面执行,所以无论是正常结束还是出现异常,都能正确关闭调用者
来一波对比
实现读取一个文件内每一行的功能
//Java 实现 FileInputStream fis = null; DataInputStream dis = null; try { fis = new FileInputStream("/home/test.txt"); dis = new DataInputStream(new BufferedInputStream(fis)); String lines = ""; while((lines = dis.readLine()) != null){ System.out.println(lines); } } catch (IOException e){ e.printStackTrace(); } finally { try { if(dis != null) dis.close(); } catch (IOException e) { e.printStackTrace(); } try { if(fis != null) fis.close(); } catch (IOException e) { e.printStackTrace(); } }
Kotlin实现
File("/home/test.txt").readLines() .forEach { println(it) }
对Kotlin就是可以两行实现。
- 仔细翻阅readLines这个扩展函数的实现你会发现,它也是间接调用了use,这样就省去了捕捉异常和关闭的烦恼
- 同样的,经过包装以后你只需要关注读出来的数据本身而不需要care各种异常情况
File的一些其它有用的扩展函数
/** * 将文件里的所有数据以字节数组的形式读出 * Tip:显然这不适用于大文件,文件过大,会导致创建一个超大数组 */ public fun File.readBytes(): ByteArray /** * 与上一个函数类似,不过这个是写(如果文件存在,则覆盖) */ public fun File.writeBytes(array: ByteArray): Unit /** * 将array数组中的数据添加到文件里(如果文件存在则在文件尾部添加) */ public fun File.appendBytes(array: ByteArray): Unit /** * 将文件以指定buffer大小,分块读出(适用于大文件,也是最常用的方法) */ public fun File.forEachBlock(action: (buffer: ByteArray, bytesRead: Int) -> Unit): Unit /** * Gets the entire content of this file as a String using UTF-8 or specified [charset]. * * This method is not recommended on huge files. It has an internal limitation of 2 GB file size. * * @param charset character set to use. * @return the entire content of this file as a String. */ public fun File.readText(charset: Charset = Charsets.UTF_8): String /** * Sets the content of this file as [text] encoded using UTF-8 or specified [charset]. * If this file exists, it becomes overwritten. * * @param text text to write into file. * @param charset character set to use. */ public fun File.writeText(text: String, charset: Charset = Charsets.UTF_8): Unit /** * Appends [text] to the content of this file using UTF-8 or the specified [charset]. * * @param text text to append to file. * @param charset character set to use. */ public fun File.appendText(text: String, charset: Charset = Charsets.UTF_8): Unit /** * Reads this file line by line using the specified [charset] and calls [action] for each line. * Default charset is UTF-8. * * You may use this function on huge files. * * @param charset character set to use. * @param action function to process file lines. */ public fun File.forEachLine(charset: Charset = Charsets.UTF_8, action: (line: String) -> Unit): Unit /** * Reads the file content as a list of lines. * * Do not use this function for huge files. * * @param charset character set to use. By default uses UTF-8 charset. * @return list of file lines. */ public fun File.readLines(charset: Charset = Charsets.UTF_8): List<String> /** * Calls the [block] callback giving it a sequence of all the lines in this file and closes the reader once * the processing is complete. * @param charset character set to use. By default uses UTF-8 charset. * @return the value returned by [block]. */ @RequireKotlin("1.2", versionKind = RequireKotlinVersionKind.COMPILER_VERSION, message = "Requires newer compiler version to be inlined correctly.") public inline fun <T> File.useLines(charset: Charset = Charsets.UTF_8, block: (Sequence<String>) -> T): T
- 上面的函数都是基于use实现的,可以放心使用,而不用担心异常的发生,并且会自动关闭IO流
-
Kotlin实战指南十九:use 函数魔法
2021-05-28 16:26:40本文出自【赵彦军的博客】 文章目录往期精彩文章use函数 往期精彩文章 Kotlin实战指南十七:JvmField、Jvm...本文章转载于:Kotlin use函数的魔法 use函数 实现了Closeable接口的对象可调用use函数 use函数会自动.转载请标明出处:http://blog.csdn.net/zhaoyanjun6/article/details/117366756
本文出自【赵彦军的博客】往期精彩文章
Kotlin实战指南十八:open、internal 关键字使用
Kotlin实战指南十七:JvmField、JvmStatic使用
Kotlin实战指南十六:Synchronized、Volatile本文章转载于:Kotlin use函数的魔法
use函数
- 实现了Closeable接口的对象可调用use函数
- use函数会自动关闭调用者(无论中间是否出现异常)
在这里插入图片描述
- 可以看出,use 函数内部实现也是通过 try-catch-finally 块捕捉的方式,所以不用担心会有异常抛出导致程序退出
- close 操作在finally里面执行,所以无论是正常结束还是出现异常,都能正确关闭调用者
下面我们就对比一下 Java 和 Kotlin 实现的不同
Java 版本
//Java 实现 FileInputStream fis = null; DataInputStream dis = null; try { fis = new FileInputStream("/home/test.txt"); dis = new DataInputStream(new BufferedInputStream(fis)); String lines = ""; while((lines = dis.readLine()) != null){ System.out.println(lines); } } catch (IOException e){ e.printStackTrace(); } finally { try { if(dis != null) dis.close(); } catch (IOException e) { e.printStackTrace(); } try { if(fis != null) fis.close(); } catch (IOException e) { e.printStackTrace(); } }
Kotlin 版本
File("/home/test.txt").readLines() .forEach { println(it) }
对
Kotlin
就是可以两行实现。仔细翻阅
readLines
这个扩展函数的实现你会发现,它也是间接调用use
,这样就省去了捕捉异常和关闭的烦恼
同样的,经过包装以后你只需要关注读出来的数据本身而不需要care
各种异常情况- File的一些其它有用的扩展函数
/** * 将文件里的所有数据以字节数组的形式读出 * Tip:显然这不适用于大文件,文件过大,会导致创建一个超大数组 */ public fun File.readBytes(): ByteArray /** * 与上一个函数类似,不过这个是写(如果文件存在,则覆盖) */ public fun File.writeBytes(array: ByteArray): Unit /** * 将array数组中的数据添加到文件里(如果文件存在则在文件尾部添加) */ public fun File.appendBytes(array: ByteArray): Unit /** * 将文件以指定buffer大小,分块读出(适用于大文件,也是最常用的方法) */ public fun File.forEachBlock(action: (buffer: ByteArray, bytesRead: Int) -> Unit): Unit /** * Gets the entire content of this file as a String using UTF-8 or specified [charset]. * * This method is not recommended on huge files. It has an internal limitation of 2 GB file size. * * @param charset character set to use. * @return the entire content of this file as a String. */ public fun File.readText(charset: Charset = Charsets.UTF_8): String /** * Sets the content of this file as [text] encoded using UTF-8 or specified [charset]. * If this file exists, it becomes overwritten. * * @param text text to write into file. * @param charset character set to use. */ public fun File.writeText(text: String, charset: Charset = Charsets.UTF_8): Unit /** * Appends [text] to the content of this file using UTF-8 or the specified [charset]. * * @param text text to append to file. * @param charset character set to use. */ public fun File.appendText(text: String, charset: Charset = Charsets.UTF_8): Unit /** * Reads this file line by line using the specified [charset] and calls [action] for each line. * Default charset is UTF-8. * * You may use this function on huge files. * * @param charset character set to use. * @param action function to process file lines. */ public fun File.forEachLine(charset: Charset = Charsets.UTF_8, action: (line: String) -> Unit): Unit /** * Reads the file content as a list of lines. * * Do not use this function for huge files. * * @param charset character set to use. By default uses UTF-8 charset. * @return list of file lines. */ public fun File.readLines(charset: Charset = Charsets.UTF_8): List<String> /** * Calls the [block] callback giving it a sequence of all the lines in this file and closes the reader once * the processing is complete. * @param charset character set to use. By default uses UTF-8 charset. * @return the value returned by [block]. */ @RequireKotlin("1.2", versionKind = RequireKotlinVersionKind.COMPILER_VERSION, message = "Requires newer compiler version to be inlined correctly.") public inline fun <T> File.useLines(charset: Charset = Charsets.UTF_8, block: (Sequence<String>) -> T): T
上面的函数都是基于use实现的,可以放心使用,而不用担心异常的发生,并且会自动关闭IO流
-
Kotlin-扩展函数use,forEachLine(第一行代码Kotlin学习笔记番外)
2021-01-04 13:17:36use是Kotlin的一个内置的扩展函数,它能保证Lambda表达式中的代码全部执行完之后自动将外层的流关闭,这样我们就不需要再写一个finally语句,手动关闭流了。使用方法如下: fun save(inputText: String) { try { ...
不了解扩展函数的,请移步 Kotlin-扩展函数和运算符重载(第一行代码Kotlin学习笔记6).1. use
use是Kotlin的一个内置的扩展函数,它能保证Lambda表达式中的代码全部执行完之后自动将外层的流关闭,这样我们就不需要再写一个finally语句,手动关闭流了。使用方法如下:
fun save(inputText: String) { try { val output = openFileOutput("data", Context.MODE_PRIVATE) val writer = BufferedWriter(OutputStreamWriter(output)) writer.use { it.write(inputText) } } catch (e: IOException) { e.printStackTrace() } }
2. forEachLine
将读到的每行内容回掉到Lambda表达式中
fun load(): String { val content = StringBuilder() try { val input = openFileInput("data") val reader = BufferedReader(InputStreamReader(input)) reader.use { reader.forEachLine { content.append(it) } } } catch (e: IOException) { e.printStackTrace() } return content.toString() }
-
Kotlin学习之关键字
2019-05-18 15:32:36Kotlin不允许声明变量但不初始化 赋非空值 var str: String = “” (…) 设为null var str: String? =null (建议这样写) 强制设为null var str: String = null!! (非常不建议) Kotlin是空安全的,但是第三种是... -
(三)Kotlin 高阶函数
2021-06-06 05:24:57一般可用于多个扩展函数链式调用 //also函数使用的一般结构 object.also{ //todo } use : use函数作用于现实了Closeable接口的类,比如文件io操作 //use函数使用的一般结构 object.use{ //todo } 例: var l = ... -
Spring Boot 与 Kotlin 使用JdbcTemplate连接MySQL
2021-01-25 19:38:48之前介绍了一些Web层的例子,包括构建RESTful API...noarg:$kotlin_version") classpath("org.jetbrains.kotlin:kotlin-allopen:$kotlin_version") } } apply plugin: 'kotlin' apply plugin: "kotlin-spring" // See ... -
kotlin学习(1) 认识kotlin中的关键字和基本用法
2020-12-12 19:06:32kotlin kotlin 是一门可以运行在jvm上的语言, 兼容java的代码。 和java的谨慎保守不同, kotlin在编码规范上进行了大量的改进, 拥有了许多java语言不支持的特性, 并且kotlin还是安卓开发的优先语言, 所以值得... -
Kotlin关键字总结
2020-07-02 14:43:38Kotlin关键字可分为三类: 1、硬关键字:这些关键字无论在什么情况下都不能用作标识符。 2、软关键字: 这些关键字可以在它们不起作用的上下文中用作标识符。 3、修饰符关键字: 这些关键字也可以在代码中用作标识符... -
Kotlin和Java混合开发总结(基于Kotlin1.3.0版本)
2019-01-15 09:30:35我本来是不想学习kotlin的,但是现在的形势,很多公司都在使用kotlin开发,可以说学会kotlin也是无奈之举,既然是潮流,谷歌也在大力推广,所以还是只能硬着头皮逼迫自己学一下,也能更快适应公司的需要。... -
kotlin基础之let、also、with、run、apply
2021-07-20 15:13:401、let的用法 1.1、let函数适用的场景 场景一: 最常用的场景就是使用let函数处理需要针对一个可null的对象统一做判空处理。 场景二: 然后就是需要去明确一...//使用kotlin mVar?.let{ it.function1(); it.function2() -
Kotlin学习(二十): Kotlin实现流的读取的方案
2018-01-22 10:11:38但是在kotlin中等式不是一个表达式,所以不能那样子写,kotlin是这样的使用的,有几种写法: 在使用流或者数据库之类的资源需要关闭 close 的情况下,可以使用 use 扩展函数来实现自动关闭的操作 第一种写法,... -
Kotlin中let、also、with、run和apply使用
2022-01-11 10:32:311、 let用户空判断 var user:User?=null user?.let{ //这里user不为null,才执行 //使用用it替代user } 返回值为函数块的最后一行或指定return表达式 ...和let类似,不同的是返回值不同,also返回传入的对象自己 ... -
kotlin中的异常处理_Kotlin中基于值的类和错误处理
2020-09-08 11:41:52kotlin中的异常处理Not to be confused with value types of project Valhalla. 不要与Valhalla项目的价值类型混淆。 Value-based classes, as defined in the Java docs, are classes which conform to a set of ... -
Kotlin基础教程之dataclass,objectclass,use函数,类扩展,socket
2020-08-30 09:50:51主要介绍了Kotlin基础教程之dataclass,objectclass,use函数,类扩展,socket的相关资料,需要的朋友可以参考下 -
Kotlin中let,apply,with,run区别
2020-09-07 15:23:39let 首先let()的定义是这样的,...with函数是一个单独的函数,并不是Kotlin中的extension,所以调用方式有点不一样,返回是最后一行,然后可以直接调用对象的方法,感觉像是let和apply的结合。 代码示例: ... -
android studio使用JDBC访问mysql数据库(Kotlin方法)
2021-02-01 07:41:33在数据test中建立table use test; create table stuinfo(id int,name varchar(20)); <1> importjava.lang.Exceptionimportjava.sql.Driverimportjava.sql.DriverManagerimportjava.sql.... -
简单理解Kotlin作用域函数run,with,let,also,apply
2018-08-09 19:07:46Kotlin标准库里面有那么几个作用域函数(run,with,let,also,apply),下面就来简单介绍一下 第一点要了解一下,Kotlin是允许函数里面定义函数的 第二点是作用域函数怎么理解(大神忽略)。一个函数一般都有花括号{ },花... -
kotlin中使用dataBinding展示图片
2018-08-16 10:24:35首先:kotlin中没有static关键字,但是提供了companion object{}代码块和使用object关键字 object关键字声明一种特殊的类,这个类只有一个实例,因此看起来整个类就好像是一个对象一样,这里把类声明时的class关键... -
Kotlin基础 — 操作符:run、with、let、also、apply、takeIf、takeUnless、repeat
2019-01-08 17:51:27Kotlin基础 — 操作符:run、with、let、also、apply、takeIf、takeUnless、repeat - Elson的博客 - CSDN博客 https://blog.csdn.net/Love667767/article/details/79376813 概述 分析Kotlin的 Standard.kt 代码... -
Kotlin使用HttpURLConnection下载文件
2019-04-26 12:24:14BufferedOutputStream(FileOutputStream("./download.png")).use { output -> input.copyTo(output) //将文件复制到本地 其中copyTo使用方法可参考我的Io流笔记 } } }catch (e : Exception){ e.printStackTrace... -
rules_kotlin:Kotlin的Bazel规则
2021-02-03 23:07:38新的优化编译路径(使用JavaBuilder)-- --define=experimental_use_abi_jars=1 。 警告:编译可能失败由于 , , 解决方法:添加tags=['kt_abi_plugin_incompatible'] 2020年12月3日。发布了版本。 包括: ... -
Kotlin-SDK:新波士顿的Kotlin-SDK
2021-05-06 15:15:41Kotlin-SDK 新波士顿的Kotlin-SDK。 介绍 这是用Kotlin为newboston编写的SDK,主要针对Android和桌面客户端。 该存储库包含一个Android项目,该项目将演示如何使用SDK。 该库本身将仅包含newboston的域和数据层。 ... -
Kotlin嵌套类和内部类
2017-12-20 23:05:43嵌套类类可以嵌套在其他类中,需要通过外部类才可以访问嵌套类的成员,外部类.嵌套类.嵌套类成员。嵌套类不能直接访问外部类的成员。class Outer { private val bar: Int = 1 class Nested { ... -
kotlin中 run、apply、let、also、with的用法和区别
2021-02-03 23:21:58run 、 apply 、 let 、 also 和 with 五个函数均位于 kotlin 包下的 Standard 文件中,其含义和用法比较相似,现分别介绍如下。 run用法1 函数定义: public inline fun run(block: () -> R): R = block() 功能... -
Kotlin 中的 let, run, with, apply, also 函数,你区分得清楚吗?
2019-08-18 18:56:51学习使用 Kotlin 有一段时间了。对于常用的几个函数: let , run , with , apply , also 却不是非常清楚了解。 本文主要内容包括:介绍 let , run , with , apply , also 函数的用法,以及它们之间的... -
Kotlin学习(十六): 关键字与操作符(Keywords and Operators)
2017-11-03 08:24:23本文同步更新于旺仔的个人博客,访问可能有点慢,多刷新几次。...硬关键字(Hard Keywords)Kotlin中的硬关键字不能作为标识符package与Java一样,Kotlin的源文件同样以包声明开始的。package foo.barfun baz() {} -
Kotlin-2.2-属性和字段
2017-12-19 23:39:38To use a property, we simply refer to it by name, as if it were a field in Java: fun copyAddress(address: Address): Address { val result = Address() // there's no 'new' keyword in Kotlin ...
收藏数
9,710
精华内容
3,884