在kotlin中打破lambda

时间:2018-05-31 09:37:51

标签: lambda kotlin kotlin-extension

我正在尝试为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(编译时错误)

2 个答案:

答案 0 :(得分: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
    }
}

答案 1 :(得分:0)

返回布尔值并不好用,正如我在上面的问题中提到的那样。 使我的扩展功能Inline解决了我的问题。

而不是

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

应该是

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

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