It it possible to break from foreachline

时间:2018-02-05 12:51:21

标签: kotlin

is it possible to break from foreachline. my code :

       fun test() {
        bufferedReader.forEachLine {
            val nameParam = it.split(":")[0]
            if (name == "test")
                return // here i wan to return from function
        }
    }

I've tried 'return@foreachline' but it just continue to next line

3 个答案:

答案 0 :(得分:2)

No, it's not: non-local returns are only supported for inline functions, and forEachLine { ... } is not an inline one, so you can only use return@forEachLine that exits the lambda.

An alternative that allows it is to read the lines first and then iterate over them:

bufferedReader.lines().use { lines ->
    for (it in lines) {
        val nameParam = it.split(":")[0]
        if (name == "test")
            break
    }
}

Here, .use { ... } ensures that the lazy Stream created by .lines() is closed once it is not needed anymore.

答案 1 :(得分:1)

Break and continue for custom control structures are not implemented yet. You could use println().

答案 2 :(得分:0)

以下简单的技巧非常好用:

 val fileToScann = File("file.txt")
        fileToScan.forEachLine {
            if( it.contains("12345") ) {
                throw Exception("line found:"+it)
            }
        }
        throw Exception("line not found")
    }