Kotlin Lambdas
Anonymous functions for concise and functional programming
🔥 What are Kotlin Lambdas?
Lambdas are anonymous functions that can be treated as values. They enable functional programming, make code more concise, and are perfect for operations like filtering, mapping, and transforming data.
// Lambda expression
val greet = { name: String -> "Hello, $name!" }
// Using the lambda
fun main() {
println(greet("Alice"))
// Lambda with list operations
val numbers = listOf(1, 2, 3, 4, 5)
val doubled = numbers.map { it * 2 }
println(doubled)
}
Output:
Hello, Alice!
[2, 4, 6, 8, 10]
Lambda Features
Concise Syntax
Short and readable code
// Lambda
val add = { a: Int, b: Int -> a + b }
Functional Style
Perfect for data transformations
// Filter and map
list.filter { it > 0 }.map { it * 2 }
First-Class Values
Can be stored and passed around
// Store in variable
val operation = { x: Int -> x * x }
Type Inference
Kotlin infers types automatically
// Type inferred from context
numbers.map { it.toString() }
🔹 Basic Lambda Syntax
Lambda expressions are enclosed in curly braces:
// Basic lambda syntax: { parameters -> body }
val square = { x: Int -> x * x }
val greet = { name: String -> "Hello, $name!" }
val add = { a: Int, b: Int -> a + b }
// Lambda with no parameters
val sayHello = { "Hello, World!" }
fun main() {
println(square(5)) // 25
println(greet("Kotlin")) // Hello, Kotlin!
println(add(3, 7)) // 10
println(sayHello()) // Hello, World!
}
Output:
25
Hello, Kotlin!
10
Hello, World!
🔹 Lambdas with Collections
Lambdas shine when working with collections:
fun main() {
val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
// Filter even numbers
val evenNumbers = numbers.filter { it % 2 == 0 }
println("Even numbers: $evenNumbers")
// Map to squares
val squares = numbers.map { it * it }
println("Squares: $squares")
// Find first number greater than 5
val firstBig = numbers.find { it > 5 }
println("First > 5: $firstBig")
// Check if any number is greater than 8
val hasLarge = numbers.any { it > 8 }
println("Has number > 8: $hasLarge")
}
Output:
Even numbers: [2, 4, 6, 8, 10]
Squares: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
First > 5: 6
Has number > 8: true
🔹 The 'it' Parameter
For single-parameter lambdas, you can use 'it' instead of declaring a parameter:
fun main() {
val words = listOf("apple", "banana", "cherry", "date")
// Using 'it' (implicit parameter)
val lengths = words.map { it.length }
val uppercase = words.map { it.uppercase() }
val startsWithA = words.filter { it.startsWith("a") }
// Equivalent with explicit parameter
val lengthsExplicit = words.map { word -> word.length }
println("Lengths: $lengths")
println("Uppercase: $uppercase")
println("Starts with 'a': $startsWithA")
println("Explicit: $lengthsExplicit")
}
Output:
Lengths: [5, 6, 6, 4]
Uppercase: [APPLE, BANANA, CHERRY, DATE]
Starts with 'a': [apple]
Explicit: [5, 6, 6, 4]
🔹 Multi-line Lambdas
Lambdas can contain multiple statements:
fun main() {
val numbers = listOf(1, 2, 3, 4, 5)
// Multi-line lambda
val processed = numbers.map { number ->
val doubled = number * 2
val message = "Processing: $number -> $doubled"
println(message)
doubled // Last expression is returned
}
println("Results: $processed")
// Another example with validation
val validNumbers = numbers.filter { num ->
val isEven = num % 2 == 0
val isPositive = num > 0
println("Checking $num: even=$isEven, positive=$isPositive")
isEven && isPositive
}
println("Valid numbers: $validNumbers")
}
Output:
Processing: 1 -> 2
Processing: 2 -> 4
Processing: 3 -> 6
Processing: 4 -> 8
Processing: 5 -> 10
Results: [2, 4, 6, 8, 10]
Checking 1: even=false, positive=true
Checking 2: even=true, positive=true
Checking 3: even=false, positive=true
Checking 4: even=true, positive=true
Checking 5: even=false, positive=true
Valid numbers: [2, 4]