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:

  1. fun main() { ... }: Entry point of the program.
  2. val list = listOf(1, 2, 3, 4, 5): Defines a immutable list containing integers from 1 to 5.
  3. val result = list.forEach { ... }: Applies the forEach function to each element of the list and executes the provided lambda expression.
  4. if (it == 3) return@forEach: Checks if the current element in the list is equal to 3. If true, it attempts to return from the forEach loop using return@forEach.
  5. println(it): Prints the current element if it doesn’t equal 3.
  6. println("Result: $result"): Prints the value of result, which is assigned the return value of the forEach function. However, in this case, it will always be Unit.

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