Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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) }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading