Returns in Lambdas

Labelled Returns

A plain return inside a lambda returns from the enclosing function (allowed only for inline functions like forEach). To skip just the current item, use a labelled return: return@forEach.

Example

fun firstNegative(nums: List<Int>): Int? {
    nums.forEach {
        if (it < 0) return it        // returns from firstNegative
    }
    return null
}

fun main() {
    println(firstNegative(listOf(3, 7, -2, -9)))

    listOf(1, 2, 3, 4, 5).forEach {
        if (it % 2 == 0) return@forEach   // like 'continue'
        print("$it ")
    }
    println()

    val words = listOf("ok", "", "fine").map label@{
        if (it.isEmpty()) return@label "(empty)"
        it.uppercase()
    }
    println(words)
}

Output

-2
1 3 5 
[OK, (empty), FINE]

Anonymous Functions

Example

An anonymous function looks like a normal function without a name. A return inside it returns from the anonymous function itself.

fun main() {
    val grade = fun(marks: Int): String {
        if (marks >= 90) return "A"
        if (marks >= 75) return "B"
        return "C"
    }
    println(listOf(95, 80, 60).map(grade))
}

Output

[A, B, C]