Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 134 ยท Functions

Lambdas

Learn Kotlin lambda expressions - syntax, the implicit it parameter, trailing lambda syntax, closures, return@label, function types and common mistakes, with runnable code.

A lambda is a function without a name that you write right where you need it. Instead of declaring fun isEven(n: Int) = n % 2 == 0 somewhere and then passing it around, you write { n -> n % 2 == 0 } on the spot. Lambdas are the reason Kotlin code can say numbers.filter { it > 3 } instead of a five-line loop, and they are the foundation of collections processing, callbacks, builders and coroutines.

Lambdas look strange for about a day and natural forever after. This lesson takes them apart piece by piece: the syntax, the shortcut it, the trailing-lambda rule, what a lambda returns, how it captures variables, and how return behaves inside one. The next lesson, Higher-Order Functions, shows how to write your own functions that take lambdas.

The syntax

A lambda is always wrapped in curly braces. Inside, parameters come first, then an arrow ->, then the body:

TEXT
{ parameter1: Type1, parameter2: Type2 -> body }

You can store a lambda in a variable and call it like a function:

Kotlin Lambdas stored in variables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

This prints 49, 7, hello from a lambda and 25. Calling square(7) is shorthand for square.invoke(7). The lambda hello has no parameters, so there is no arrow at all. The type of each variable is a function type: square is (Int) -> Int, add is (Int, Int) -> Int and hello is () -> Unit. You can write that type out yourself, which then lets you drop the parameter types inside the lambda, because the compiler already knows them:

Kotlin
val square: (Int) -> Int = { x -> x * x }

Function types get a lesson of their own, Function Types and Type Aliases. For now remember the shape: parameter types in parentheses, an arrow, the return type.

Inference needs a type from somewhere

The compiler cannot guess parameter types out of thin air. Either you write the types inside the lambda, or you write the variable's function type, or the lambda is passed to a function that already declares the parameter type. If the shapes disagree, you get an error:

Kotlin A lambda with the wrong number of parameters (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler says main.kt:2:30: error: initializer type mismatch: expected '(Int, Int) -> Int', actual '(Int) -> Int'. The declared type wants two parameters, but the lambda takes one. Write { x, y -> x * 2 } (or use x + y) to match.

The result is the last expression

A lambda has no return keyword for its normal result. The last expression in the body is the value of the lambda. Earlier lines are ordinary statements:

Kotlin The last expression is the result

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The first two calls print 8 is even and small and 251 is odd and big. The string template on the last line is what the lambda returns. noResult ends with println(...), which returns Unit, so r is Unit and the last line prints kotlin.Unit. If you want to be sure a lambda returns nothing, declare its type as () -> Unit; the compiler then ignores the last expression's value.

The implicit parameter it

When a lambda has exactly one parameter, you may leave out the parameter list and the arrow. The parameter is then available under the name it:

Kotlin it for single-parameter lambdas

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

You get [1, 4, 9, 16, 25, 36], [2, 4, 6], true, [KIWI, BANANA, FIG] and [fig, kiwi, banana]. Use it for short lambdas where the meaning is obvious from the surrounding call. Switch to a named parameter when the lambda is longer than a line or two, when lambdas are nested (two different its in one expression confuse readers), or when the name adds meaning, as in users.filter { user -> user.isActive }.

Unused parameters and destructuring

If a lambda has several parameters and you don't use one, replace its name with an underscore. Lambdas can also destructure a Pair or a map entry in the parameter list:

Kotlin Underscore and destructuring in lambdas

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Note the double parentheses: { (name, score) -> ... } has one parameter (the map entry), destructured into two names. Without the parentheses it would declare two parameters. The underscore in (_, score) says "I don't need the key". More about this in Pairs, Triples and Destructuring.

Trailing lambda syntax

When the last parameter of a function is a function, you may write the lambda outside the parentheses. If it is the only argument, the parentheses can go away entirely. This reads like a language feature, and it is what makes repeat(3) { ... } and builders possible.

Kotlin Three ways to write the same call

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

All three filter calls are identical, so the first line prints true, followed by [3, 8, 9]. The fold call passes 0 in parentheses and the lambda after them: fold(initial) takes the lambda as its last parameter. It prints 21. repeat(2) calls the lambda with 0 and then 1, so it prints round 0 and round 1. In everyday code you will nearly always see the third form.

Lambdas capture their surroundings

Like local functions, a lambda is a closure. It can read and change variables from the code around it, even long after that code has run. This is how a counter works:

Kotlin Closures remember their variables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The three calls on a print 0, 1, 2, because count++ returns the old value. The counter b has its own count, so it starts again at 0. Each call to makeCounter creates a new variable, and the returned lambda keeps it alive after makeCounter has returned. Finally forEach adds into the outer sum, which ends at 60. In Java, captured variables must be effectively final; Kotlin has no such limit, and boxes mutable captured variables for you.

A lambda that escapes (returned, stored, or handed to another thread) keeps everything it captured alive. A lambda capturing a huge list prevents that list from being garbage collected. Keep escaping lambdas small and capture only what they need.

return inside a lambda

Plain return inside a lambda is a puzzle: does it return from the lambda or from the function that contains it? Kotlin answers by context.

For a lambda stored in a variable or passed to an ordinary function, a bare return is simply not allowed:

Kotlin return in a normal lambda (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

You get main.kt:3:20: error: 'return' is prohibited here. To leave a lambda early, use a labeled return. Each lambda passed to a function foo gets the implicit label @foo, or you can name it yourself with label@:

Kotlin Labeled returns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The two calls to f print 4 and -1. In forEach, return@forEach skips only the current element, like continue in a loop, so you see saw 1, saw 2, saw 4 and then done.

There is one more case. Lambdas passed to inline functions such as forEach, map or let may use a bare return, which then returns from the enclosing function. That is called a non-local return:

Kotlin Non-local return from an inline lambda

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Here return it leaves firstNegative entirely, so the output is -2 and null. This only works because forEach is inline; the inline functions lesson explains why. Do not use it if a loop reads more clearly: for (n in numbers) if (n < 0) return n does the same job.

Passing existing functions instead of lambdas

If a lambda only forwards its argument to an existing function, pass the function by reference with ::. Both lines below do the same:

Kotlin Function references versus lambdas

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The first two lines both print [kiwi, fig]. The third prints [KIWI, BANANA, FIG, CHERRY]. See Higher-Order Functions for all the reference forms.

Anonymous functions

Kotlin has a second way to write a function without a name: the anonymous function. It looks like a normal function declaration with the name left out:

Kotlin
val isEven = fun(n: Int): Boolean { return n % 2 == 0 }

Why have two forms? They differ in three small ways. An anonymous function declares its return type explicitly (or uses an = body), it uses a plain return that returns from the anonymous function itself, and it can only be passed inside the parentheses of a call, never after them as a trailing lambda. A plain return inside a lambda, by contrast, would try to leave the enclosing function (see the previous section).

Kotlin Anonymous function versus lambda

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The anonymous function with return false for small numbers is the readable way to write a function with several exits. In a lambda you would have to use a label (return@filter false) or rewrite it as an expression. In everyday code lambdas win for short bodies, and anonymous functions are rare, but you will see them in older code and whenever a multi-exit body is clearer.

A function literal with receiver

Both forms can also have a receiver: the function type T.() -> R means "a function you call on a T". Inside the body, this is the receiver and you can call its members without a prefix. This is the idea behind apply, buildString and every DSL:

Kotlin Function literals with receiver

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Notice that "hello".shout() looks like a call to an extension function, because a function with receiver is exactly that, just as a value. A normal function type (String) -> String and the receiver type String.() -> String are interchangeable at the type level, so you can pass one where the other is expected, but the receiver version reads better when the function configures or extends an object.

Style tips

  • Keep lambdas short. If you need more than three or four lines, give the logic a name as a function and pass a reference.
  • Use it only when the meaning is obvious; otherwise name the parameter.
  • Prefer the trailing-lambda form, and drop empty parentheses.
  • Avoid side effects in map and filter lambdas. Those functions are for computing a value; use forEach or a for loop for effects.
  • A lambda that is only { it } or { x -> foo(x) } can often be replaced by a reference or by the function itself.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the value of this lambda: { a: Int, b: Int -> a + b } when called with (2, 3)?

    The last expression of a lambda is its result, so the lambda returns a + b, which is 5.
  2. 2. When can you use the implicit name it?

    it is available when the lambda has a single parameter and you leave out the parameter list and the arrow.
  3. 3. Which call is written with trailing lambda syntax?

    When the last parameter is a function, the lambda may be placed outside the parentheses, and empty parentheses can be dropped.
  4. 4. Inside listOf(1, 2, 3).forEach { ... }, what does return@forEach do?

    A labeled return leaves only the lambda, so forEach continues with the next element, like continue in a loop.
  5. 5. What happens to count after makeCounter() has returned the lambda { count++ }?

    A lambda is a closure: it keeps the variables it captured alive for as long as the lambda exists, and each call of makeCounter creates a fresh variable.

Summary

  • A lambda is a function literal in braces: { a: Int, b: Int -> a + b }; its type is a function type like (Int, Int) -> Int.
  • The last expression is the result; a lambda ending in println gives back Unit.
  • A one-parameter lambda can use it; use _ for unused parameters and (a, b) to destructure.
  • If the last parameter is a function, put the lambda outside the parentheses.
  • Lambdas are closures: they capture and may modify outer variables.
  • Use return@label to leave a lambda; a bare return is allowed only in inline lambdas, where it returns from the enclosing function.

Next: Higher-Order Functions