0

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

1
  • return@forEach does not mean to return from the forEach() function. It means returning from the lambda passed to forEach(). Commented Nov 9, 2021 at 19:31

1 Answer 1

5

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) }
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer, you are right I may not need to write such a thing but I am just doing it for the sake of learning. So the simple answer I guess would be, the return@forEach returns from the lambda passed to forEach not from the whole forEach. Am I right?
Yes, that's a good way to put it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.