【问题标题】:Break out of lambda in kotlin在 kotlin 中突破 lambda
【发布时间】:2018-05-31 09:37:50
【问题描述】:

我正在尝试向 Java 的 InputStream 类添加一个非常有用的扩展方法,因为我们知道流解析需要几行样板代码,并且在我的应用程序中,我们需要多次处理流。

到目前为止,我的扩展功能可以正常工作,但是对于我们在使用 kotlin 核心语言功能时面临的一些缺点来说,它确实非常有用。

我对 Java Stream 的扩展函数接受单参数方法定义。

fun InputStream.forEachLine(consumer: (line: String)->Unit){
    val reader = BufferedReader(InputStreamReader(this, Charset.defaultCharset()))
    var line: String? = null
    line = reader.readLine()
    while (line != null) {
        consumer(line)
        line = reader.readLine()
    }
}

//My Test is here
@Test
fun testExtnInputStreamForEachLine() {
    val stream = FileInputStream(File("c:\temp\sometextfile.txt"))
        stream.forEachLine {
            println(it)

            if(it.equals("some text")
            // I want to break the whole forEachLine block 

        }
}

在上面的例子中,我有以下方法:

  • return@forEachLine(这对于跳过同一个块很有用 处理,类似于继续)
  • 创建了一个带有标签的run 块并尝试在其上返回。 (给出编译时错误)
  • break@withLabel(编译时错误)
  • 更改了返回 boolean 而不是 Unit 的方法并尝试返回 false(编译时错误)

【问题讨论】:

标签: lambda kotlin kotlin-extension


【解决方案1】:

改成:consumer: (line: String) -> Boolean 像这样:

fun InputStream.forEachLine(consumer: (line: String) -> Boolean){
    val reader = BufferedReader(InputStreamReader(this, Charset.defaultCharset()))
    var line: String? = null
    line = reader.readLine()
    while (line != null) {
        if (consumer(line))
            break
        line = reader.readLine()
    }
}

//My Test is here
@Test
fun testExtnInputStreamForEachLine() {
    val stream = FileInputStream(File("c:\temp\sometextfile.txt"))
    stream.forEachLine {
        println(it)
        if(it.equals("some text")) true else false
    }
}

【讨论】:

    【解决方案2】:

    正如我在上面的问题中提到的那样,返回布尔值并不好。 将我的扩展功能设置为内联解决了我的问题。

    代替

    fun InputStream.forEachLine(consumer: (line: String)->Unit){
    

    应该是

    inline fun InputStream.forEachLine(consumer: (line: String)->Unit){
    

    注意上面的 Inline 关键字,有了它,它现在允许我们通过支持返回和返回标签来从循环中存在。

    【讨论】:

      猜你喜欢
      • 2018-01-27
      • 2019-05-13
      • 1970-01-01
      • 1970-01-01
      • 2017-03-26
      • 2017-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多