Kotlin学习(二十): Kotlin实现流的读取的方案
在Java对流的读取是下面的那样,当前不要忘记流的关闭close。
// java 代码 void someFunc(InputStream in, OutputStream out) throws IOException { int read; while ((read = in.read()) != -1) { out.write(read); } }
但是在kotlin中等式不是一个表达式,所以不能那样子写,kotlin是这样的使用的,有几种写法: 在使用流或者数据库之类的资源需要关闭close的情况下,可以使用use扩展函数来实现自动关闭的操作
第一种写法,文艺青年: 通过闭包返回来实现
fun someFunc(`in`: InputStream, output: OutputStream) { try { var read: Int = -1 `in`.use { input -> output.use { while ({ read = input.read();read }() != -1) { it.write(read) } } } } catch (t: Throwable) { t.printStackTrace() } }
第二种写法,二逼青年:
通过正常写法来实现
fun someFunc(`in`: InputStream, output: OutputStream) { try { var read: Int = `in`.read() `in`.use { input -> output.use { while (read != -1) { it.write(read) read = input.read() } } } } catch (t: Throwable) { t.printStackTrace() } }
第三种写法,优秀青年:
通过使用also扩展函数来实现
fun someFunc(`in`: InputStream, output: OutputStream) { try { var read: Int = -1 `in`.use { input -> output.use { while (input.read().also { read = it } != -1) { it.write(read) } } } } catch (t: Throwable) { t.printStackTrace() } }
我们来看一下also函数是什么样的:
also函数,传入一个拉姆达并且调用,拉姆达的参数是调用also的实例,然后返回实例,很好理解,就是哪个调用的就返回哪个,并且将它传入拉姆达里面。
举个栗子:
data class User(val name: String, val age: Int) fun getMain() { val userOut = User("jowan", 25) println(userOut.also { println("also---$it") // 这里的it表示什么,同时打印什么 }) // 这里会打印什么 }
打印什么应该猜到了吧!!
以上代码参考了萌雀julao的博客,如有疑问,请各种方式私聊我。
上一篇:
IDEA上Java项目控制台中文乱码