Junior — Middle
Can you explain what a lambda expression is in Kotlin and how it is used?
sobes.tech AI
Answer from AI
A lambda expression in Kotlin is an anonymous function that can be passed as a value, stored in variables, and used for concise function notation.
They are often used for collection processing, callbacks, and simplifying code.
Example of a lambda expression:
val sum = { a: Int, b: Int -> a + b }
println(sum(3, 4)) // Outputs 7
Usage with collections:
val numbers = listOf(1, 2, 3, 4)
val doubled = numbers.map { it * 2 }
println(doubled) // [2, 4, 6, 8]
Here, { it * 2 } is a lambda where it is the current list element.
Lambdas make code compact and convenient for functional programming styles.