← Back to Kotlin Course | Chapter 9: Lambdas & Higher-Order Functions | Lesson 1 of 6

Lambda Syntax

A lambda is a tiny nameless function you can write on the spot and hand to someone else, like a sticky note with instructions.

Writing a Basic Lambda

A lambda is written inside curly braces, with parameters (if any) listed before an arrow ->, followed by the body. The last expression in the body becomes the lambda's result.

Example: Writing a Basic Lambda

markup
fun main() {
    val square = { x: Int -> x * x }
    println("Square of 5: ${square(5)}")
}

Lambdas with No Parameters

When a lambda takes no parameters, the arrow and parameter list are simply omitted, leaving just the body inside the braces.

Example: Lambdas with No Parameters

markup
fun main() {
    val sayHello = { println("Hello from a lambda!") }
    sayHello()
}

Lambdas with Multiple Parameters

A lambda can take several parameters, separated by commas before the arrow, just like a regular function's parameter list.

Example: Lambdas with Multiple Parameters

markup
fun main() {
    val add = { a: Int, b: Int -> a + b }
    println("Sum: ${add(3, 4)}")
}

Passing a Lambda to a Function

Lambdas are often written directly at the call site of a function that expects one, such as with collection operations, rather than being stored in a variable first.

Example: Passing a Lambda to a Function

markup
fun main() {
    val numbers = listOf(1, 2, 3, 4)
    val doubled = numbers.map { n -> n * 2 }
    println(doubled)
}
Common Mistakes
  1. Forgetting the arrow -> that separates a lambda's parameters from its body when parameters are explicitly named.
  2. Adding unnecessary parentheses around a lambda's parameter list; lambda parameters are not wrapped in () like a regular function's are.
  3. Trying to write return inside a lambda assigned to a variable and expecting it to just exit the lambda, when it actually performs a non-local return if the lambda is inlined.
Chapter Summary
  • A lambda expression is written as { parameters -> body }, and can be assigned to a variable or passed directly to a function.
  • If a lambda has no parameters, the -> and everything before it is omitted entirely.
  • The last expression inside a lambda's body is automatically its return value.
  • Lambdas can be stored in variables with a function type, such as val add: (Int, Int) -> Int.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.