Lambda
- Kotlin course
- Intermediate
- Lesson 54/116
- 5 min
Learn lambda expressions with { x -> x * 2 }.
Lambda
A lambda is a function without a name. It is written as { x -> x * 2 }; the parameter and body sit inside curly braces.
Example: val double: (Int) -> Int = { x -> x * 2 }. This lambda takes an Int and returns twice its value. Calling double(5) returns 10. Lambdas can be assigned to variables, passed as parameters or used in collection methods. When the lambda is the last parameter, Kotlin lets you place it outside the parentheses.
Lambda call
After a lambda is assigned to a variable, it is called by the variable name. The invoke method also works.
Example: val double: (Int) -> Int = { x -> x * 2 }. Calling double(5) or double.invoke(5) returns 10. The lambda type is (Int) -> Int; parameter and return types are explicit. Lambdas are ideal for short one-line helpers. For long bodies, a fun declaration is preferred.
Practice The double lambda
Declare val double: (Int) -> Int = { x -> x * 2 }. In main call println(double(5)).
Starter code
// a double lambda of function type
// x -> x * 2 body
// call it in main and printSample solution
val double: (Int) -> Int = { x -> x * 2 }
fun main() {
println(double(5))
}Expected output
10
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the lambda parts
| Term | Meaning |
|---|---|
{ x -> ... } |
Lambda syntax |
x |
Parameter |
x * 2 |
Body |
double(5) |
Call |
2 How is a <strong>lambda</strong> called?
- Only with invoke
- By the variable name, in parentheses Correct answer
- Only with fun
- With return
Explanation: A lambda is called by the variable name with the argument in parentheses.
3 Complete the lambda definition
val double: (Int) -> Int = { ____ -> x * 2 }
val double: (Int) -> Int = { x -> x * 2 }
Explanation: x is the lambda parameter.