美文网首页
Kotlin高阶函数with,use使用

Kotlin高阶函数with,use使用

作者: 微风细雨007 | 来源:发表于2019-03-01 12:31 被阅读0次

高阶函数是将函数用作参数或返回值的函数。

中文官方文档

创建一个hello.txt文件

import java.io.BufferedReader
import java.io.FileReader

fun main(args: Array<String>) {
    ioWith()
    ioReadText()
    ioUse()
}

fun ioUse() {
    BufferedReader(FileReader("hello.json")).use {
        var line: String?
        while (true) {
            line = it.readLine() ?: break
            println(line)
        }
    }
}

fun ioReadText() {
    val text = BufferedReader(FileReader("hello.json")).readText()
    println(text)

}

fun ioWith() {
    val bufferedReader = BufferedReader(FileReader("hello.txt"))
    with(bufferedReader) {
        var line: String?
        while (true) {
            line = readLine() ?: break
            println(line)
        }
        close()
    }
}

相关文章

网友评论

      本文标题:Kotlin高阶函数with,use使用

      本文链接:https://www.haomeiwen.com/subject/iztduqtx.html