Lambdas
Kotlin lambdas are first-class function literals. With trailing-lambda syntax + it, higher-order operations stay terse without going cryptic.
Lambda patterns
EXAMPLE
// 1) The shapes
val add: (Int, Int) -> Int = { a, b -> a + b }
val square: (Int) -> Int = { it * it } // 'it' = the single param
add(2, 3) // 5
square(5) // 25
// 2) Standard library — sort / filter / map / fold
val nums = listOf(1, 2, 3, 4, 5)
nums.map { it * 2 } // [2, 4, 6, 8, 10]
nums.filter { it % 2 == 0 } // [2, 4]
nums.fold(0) { acc, n -> acc + n } // 15
nums.maxBy { -it } ?: 0
nums.groupBy { if (it % 2 == 0) "even" else "odd" }
// 3) Trailing-lambda syntax + DSLs
fun retry(times: Int = 3, block: () -> String): String {
repeat(times - 1) {
try { return block() } catch (_: Exception) { /* retry */ }
}
return block()
}
val body = retry(times = 5) { httpGet("https://api.example.com") }
// 4) Receivers — lambdas with a receiver are how DSLs read so cleanly
fun buildString2(block: StringBuilder.() -> Unit): String {
val sb = StringBuilder()
sb.block()
return sb.toString()
}
val msg = buildString2 {
append("Hello, ")
append("world")
appendLine('.')
}
// 5) Scope functions — let / run / apply / also / with
val len = name?.let { it.length } ?: 0 // smart-cast, only if non-null
val user = User().apply { // mutate, return receiver
name = "Ada"; age = 36
}
val msg2 = with(user) { "$name ($age)" } // shorter access to receiver
// 6) Function references
val lengths = listOf("Ada", "Bo", "Cy").map(String::length)
val users = ids.mapNotNull(::findUser)
// 7) inline — zero-cost higher-order functions
inline fun measure(block: () -> Unit): Long {
val start = System.nanoTime()
block()
return System.nanoTime() - start
}
// 8) Filter null vs nullable lambda
val names: List<String?> = listOf("Ada", null, "Bo")
val clean: List<String> = names.filterNotNull()
Why it matters
it + trailing-lambda + scope functions are why Kotlin DSLs read so naturally. Reach for them; explicit parameter names + non-trailing lambdas are noise in 90% of real code.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Example
Example
val nums = listOf(1, 2, 3, 4)
val doubled = nums.map { it * 2 }
val evens = nums.filter { it % 2 == 0 }
val total = nums.sum()
Try it Yourself »
Discussion
Loading…