圖片來源網絡
在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
擴展函數來實現自動關閉的操作
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
函數,傳入一個拉姆達并且調用,拉姆達的參數是調用also
的實例,然后返回實例,很好理解,就是哪個調用的就返回哪個,并且將它傳入拉姆達里面。
舉個栗子:
data class User(val name: String, val age: Int)
fun getMain() {
val userOut = User("jowan", 25)
println(userOut.also {
println("also---$it") // 這里的it表示什么,同時打印什么
}) // 這里會打印什么
}
打印什么應該猜到了吧!!
result
以上代碼參考了萌雀julao的博客,如有疑問,請各種方式私聊我。