Interview QuestionPractical QuestionFollow-up Questions

Lambda Expressions in Kotlin

skydovesJaewoong Eum (skydoves)||9 min read

Lambda Expressions in Kotlin

A lambda expression is an anonymous function that can be treated as a value. You can pass it as an argument to another function, return it, or store it in a variable. Lambdas are a foundational feature of Kotlin's functional programming support and appear throughout the standard library, Jetpack Compose, and coroutine APIs. By the end of this lesson, you will be able to:

  • Describe the syntax of a lambda expression and how the compiler infers types.
  • Use the implicit it parameter for single parameter lambdas.
  • Explain how lambdas capture variables from their enclosing scope.
  • Apply trailing lambda syntax to write concise function calls.

Lambda Syntax

A lambda expression is enclosed in curly braces. If it has parameters, they appear before the -> symbol, followed by the body. The last expression in the body is the return value:

val greet: (String) -> String = { name ->
    "Hello, $name"
}
println(greet("skydoves")) // Output: Hello, skydoves

When the compiler can infer the parameter types from context, you can omit the type annotations. This is common when passing a lambda to a function that declares the expected function type in its signature.

A lambda with no parameters omits the -> entirely. The body is the only content between the braces:

val sayHello = { println("Hello, World!") }
sayHello() // Output: Hello, World!

For lambdas with multiple parameters, each parameter is listed before the arrow, separated by commas. Destructuring declarations are also supported, which is useful when working with pairs or map entries:

val map = mapOf("a" to 1, "b" to 2)
map.forEach { (key, value) ->
    println("$key = $value")
}

The Implicit it Parameter

When a lambda has exactly one parameter, Kotlin allows you to skip the parameter declaration and use the implicit name it instead:

val numbers = listOf(1, 2, 3, 4, 5)
val squared = numbers.map { it * it }
println(squared) // Output: [1, 4, 9, 16, 25]

This shorthand keeps code concise for simple transformations. For lambdas with multiple parameters or when the meaning of it is ambiguous, declaring explicit names improves readability.

Trailing Lambda Syntax

When the last parameter of a function is a function type, Kotlin lets you move the lambda outside the parentheses. If the lambda is the only argument, you can omit the parentheses entirely:

val longNames = listOf("Alice", "Bob", "Charlie")
    .filter { it.length > 3 }
println(longNames) // Output: [Alice, Charlie]

This syntax is what makes Kotlin DSLs and Compose UI declarations read naturally. A function like Column { ... } in Compose uses trailing lambda syntax to accept its content composable.

This interview continues for subscribers

Subscribe to Dove Letter for full access to exclusive interviews about Android and Kotlin development.

Become a Sponsor