Search code examples
kotlinlambdareturn

Return from lambda in Kotlin


I am new the Kotlin programming and getting confused about returning something from a lambda. I think I understood the most but the following code is really creating problem to me.

When it is written that if(it==0) return@forEach then it should mean that return out of the forEach loop. Or in other words, exit the forEach loop. But it still continues to check the remaining items in the list.

Here is the code I am following

fun main(args: Array<String>) {

 val listOf10 = listOf(2, 4, 0, 9, 8)

 listOf10.forEach {
    if (it == 0) return@forEach
    println(it)
 }

}

The expected output is 2,4 but it gives 2,4,9,8. Can anyone here help me out with this?

Thank you


Solution

  • The lambda passed to the forEach function is invoked repeatedly for every item in the iterable, so if you return from the lambda early, you're only returning from that iterative call of the lambda.

    You can break out of the function using a label on a run scope function lambda, but it's clumsy:

    run {
        listOf10.forEach {
            if (it == 0) return@run
            println(it)
        }
    }
    

    Normally, you should not have much need for this, because forEach is intended for tacking onto the end of a chain of functional calls. When you simply want to iterate from a variable directly, you should use a traditional for loop. See here in the Kotlin Coding Conventions. For example:

    for (it in listOf10) {
        if (it == 0) break
        println(it)
    }
    

    When you're working with a chain of functional calls, you typically use other operators to control/filter what you want to iterate and tack a forEach call at the end after it's filtered. For example:

    listOf10.takeWhile { it != 0 }
        .forEach { println(it) }