Lesson 10 of 17

Lambdas

Lambda Expressions

Lambdas are anonymous functions you can store in variables or pass to other functions:

val double = { x: Int -> x * 2 }
println(double(5))   // 10

The syntax is { parameters -> body }. For multiple parameters:

val add = { x: Int, y: Int -> x + y }
println(add(3, 4))   // 7

Lambdas can be passed to functions that expect a function type:

val nums = listOf(1, 2, 3)
val doubled = nums.map { it * 2 }  // [2, 4, 6]

When there's only one parameter, Kotlin provides the implicit name it.

Your Turn

Create a lambda square that squares a number, and a lambda isEven that returns true if a number is even. Apply them to a list.

JS Transpiler loading...
Loading...
Click "Run" to execute your code.