Jonny
Jonny

Reputation: 306

It it possible to break from foreachline

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

Upvotes: 4

Views: 2052

Answers (4)

Prilaga
Prilaga

Reputation: 857

You can use iterator and run{} block to exit from forEach.

var hasTestLine = false
textFile.bufferedReader().use { reader ->
    run {
        reader.lineSequence().iterator().forEach { line ->
            if (line == "test") {
                hasTestLine = true
                return@run
            }
        }
    }
}

Upvotes: 0

Interkot
Interkot

Reputation: 737

The following simple hack works perfectly fine:

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

Upvotes: 1

hotkey
hotkey

Reputation: 147961

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.

Upvotes: 6

Mani7TAM
Mani7TAM

Reputation: 469

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

Upvotes: 1

Related Questions