Thuta Learning
AdvancedProgrammingbeginner

Lambdas

Relax. We'll talk through this in plain words — no textbook voice.

A lambda is a kind of function without a name. You can treat a function like a value — store it in a variable, pass it as a parameter, or use it directly in collection operations. In Kotlin collections' map, filter, forEach methods, you'll see lambdas everywhere.

kotlin
fun main() {
    val sum = { x: Int, y: Int -> x + y }
    println("Sum of 5 and 3 is ${sum(5, 3)}")
}
You should see
Sum of 5 and 3 is 8

Summary

Lambdas make Kotlin expressive and turn collection processing into something effortless.

Easy traps

  • It's easy to get confused not realizing that the last expression in a lambda body is its return value.

Practical example — names formatting

Practical example — names formatting

kotlin
fun main() {
    val names = listOf("aung", "hla", "su")
    val formatted = names.map { it.uppercase() }

    println(formatted)
}

You'll know it worked when: [AUNG, HLA, SU]

Lambdas | Thuta Learning