return@foreach not working kotlin
fun main() {
val list = listOf(1, 2, 3, 4, 5)
val result = list.forEach {
if (it == 3) return@forEach
println(it)
}
println("Result: $result")
}
The code provided demonstrates the use of forEach
with a return@forEach
statement in Kotlin. It attempts to print each element of a list except when the element is equal to 3. However, the return@forEach
statement here doesn't terminate the main()
function as expected.
Explanation:
fun main() { ... }
: Entry point of the program.val list = listOf(1, 2, 3, 4, 5)
: Defines a immutable list containing integers from 1 to 5.val result = list.forEach { ... }
: Applies theforEach
function to each element of the list and executes the provided lambda expression.if (it == 3) return@forEach
: Checks if the current element in the list is equal to 3. If true, it attempts to return from theforEach
loop usingreturn@forEach
.println(it)
: Prints the current element if it doesn’t equal 3.println("Result: $result")
: Prints the value ofresult
, which is assigned the return value of theforEach
function. However, in this case, it will always beUnit
.
The issue here is that return@forEach
only returns from the current lambda expression, not from the main()
function. Therefore, the output will be:
1
2
4
5
Result: kotlin.Unit