Kotlin Lambdas — Anonymous Functions Explained
A lambda is a function literal — a function without a name that can be stored in a variable or passed as a parameter.
What You Will Learn
- Lambda syntax
- The it implicit parameter
- Store lambdas in variables
- Pass lambdas to map, filter, forEach
- Capture variables from outer scope
Lambda Syntax
Basic Lambda
fun main() {
val double: (Int) -> Int = { n -> n * 2 }
val shout: (String) -> String = { s -> s.uppercase() + "!" }
println(double(5))
println(shout("kotlin"))
val sum: (Int, Int) -> Int = { a, b -> a + b }
println(sum(3, 7))
}(Int) -> Int is the function type. { n -> n * 2 } is the lambda. n is the parameter, n * 2 is the body and implicit return value.
The "it" Parameter
Using it
fun main() {
val double: (Int) -> Int = { it * 2 }
val nums = listOf(1, 2, 3, 4, 5)
println(nums.map { it * 3 })
println(nums.filter { it % 2 == 0 })
println(nums.forEach { println(it) })
}"it" refers to the single lambda parameter. This is idiomatic Kotlin — use it for short, clear lambdas.
Lambdas with Collections
Collection Operations with Lambdas
fun main() {
val names = listOf("Alice","Bob","Carol","Dave")
val long = names.filter { it.length > 3 }
val upper = names.map { it.uppercase() }
val joined = names.joinToString(", ")
val total = listOf(1,2,3,4,5).reduce { acc, n -> acc + n }
println(long)
println(upper)
println(joined)
println(total)
}filter keeps elements where the lambda returns true. map transforms each element. reduce accumulates a single result.
Closures — Capturing Variables
Closure
fun main() {
var count = 0
val increment = { count++ }
increment()
increment()
increment()
println(count)
}The lambda captures the count variable from the outer scope and increments it each time it is called.
Practice Exercise
What prints? val nums = listOf(1,2,3,4,5) println(nums.filter { it > 3 }.map { it * 10 })
Quick Quiz
What is "it" in a Kotlin lambda?
Frequently Asked Questions
Related Tutorials
Written by KotlinGuide Editorial Team · Reviewed by KotlinGuide Technical Review