Kotlin — Lambdas
Basic lambda
fun main() {
val add = { a: Int, b: Int -> a + b }
println(add(3, 4)) // 7
val greet = { name: String -> println("Hello, $name!") }
greet("Alice")
}
Trailing lambda
fun main() {
val nums = listOf(1, 2, 3, 4, 5)
// Trailing lambda syntax
val evens = nums.filter { it % 2 == 0 }
println(evens) // [2, 4]
nums.forEach { println(it) }
}
It keyword
fun main() {
val nums = listOf(1, 2, 3, 4, 5)
nums.filter { it > 2 }.forEach { println(it) }
// 3 4 5
}
Higher-order functions
fun applyOp(a: Int, b: Int, op: (Int, Int) -> Int): Int {
return op(a, b)
}
fun main() {
println(applyOp(3, 4) { a, b -> a + b }) // 7
println(applyOp(3, 4) { a, b -> a * b }) // 12
}
Collection operations
fun main() {
val nums = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val result = nums
.filter { it % 2 == 0 }
.map { it * it }
.sorted()
.take(3)
.sum()
println(result) // 20 (4 + 16 + 36)
}
Function references
fun isEven(n: Int) = n % 2 == 0
fun main() {
val nums = listOf(1, 2, 3, 4, 5)
val evens = nums.filter(::isEven)
println(evens) // [2, 4]
}
Mini Practice
Write Kotlin code that:
- Creates a lambda and passes it as an argument
- Chains
filter,map, andreducewith lambdas - Uses function references with
:: - Creates a higher-order function
Up Next
In the next lesson, you'll learn about Extensions — extending existing classes.
Related Topics
Frequently Asked Questions about Lambdas
What is Lambdas in Kotlin?
Lambdas is a fundamental concept in Kotlin. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Lambdas?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Lambdas.
Why is Lambdas important in Kotlin?
Lambdas is essential for Kotlin development. Understanding this concept will help you write better code and solve real-world problems more effectively.