Functions and lambdas
Why it matters
- Android code is full of lambdas: click listeners, Compose events,
map,filter, coroutine builders. You write them all day. - A bare
returninside a lambda can quietly stop a whole function. This is a real production bug. - A lambda that captures your Activity can keep it in memory after the screen is gone.
- Interviewers ask about
inline,noinline,crossinlineand closures to see if you know what the compiler does.
The simple explanation
Think of a recipe card you hand to a cook. The card is the function. A lambda is a small card you write on the spot and give to someone else to run when needed: "when the dough is ready, do this".
- A higher-order function is a function that takes such a card, or gives one back.
- A closure is a card that remembers things from the room where it was written, such as the oven number. It keeps using that oven even later.
- inline means: do not hand over the card, copy its steps straight into the recipe.
The real names:
| Idea | Kotlin | Example |
|---|---|---|
| Function type | (Int) -> String | takes an Int, returns a String |
| Lambda | { x -> x + 1 } | one parameter can be called it |
| Trailing lambda | button.setOnClickListener { ... } | last lambda goes outside the brackets |
| Function reference | items.forEach(::println) | pass an existing function as a value |
| Default argument | fun f(a: Int = 0) | evaluated on every call |
| Named argument | f(a = 1) | order does not matter |
| SAM interface | fun interface Click | one method, can be written as a lambda |
| No result | Unit | like void, but it is a real type |
Notes
- A lambda returns its last expression. You cannot write a plain
returnto give the value back. - Default arguments are evaluated on each call, not once. A default like
System.currentTimeMillis()is fresh every time. - Named arguments make boolean flags readable:
show(animated = false). Use them when a call has two or more parameters of the same type. varargtakes many values. Pass an existing array with the spread operator:f(*array).- A closure captures variables, not copies. A captured
varis wrapped in a small holder object so the lambda and the function share it. - A lambda that uses
this(a member of your class) holds a reference to that object. In a long-lived place this is a memory leak. inlinecopies the function body and the lambda into each call site. It removes the lambda object and the call. Use it for small functions that take lambdas, such asforEach,let,repeat.- Only inline lambdas allow a non-local return: a bare
returnleaves the enclosing function. Usereturn@forEachto only leave the lambda. noinlinemarks a lambda parameter that you want to store or pass on as a value.crossinlineforbids non-local return because the lambda runs in another context, for example inside aRunnable.- Do not mark big functions
inline. The body is copied at every call site and bytecode grows. - For Java callers, default arguments are invisible unless you add
@JvmOverloads. This matters for customViewconstructors used from XML. - Scope functions (
let,apply,run), extension functions and generics get their own lessons later in this module.
Code example
A price formatter with default and named arguments, a retry helper that takes a lambda, and a SAM interface.
// Default and named arguments replace many overloads.
fun formatPrice(cents: Long, currency: String = "USD", withCode: Boolean = true): String {
val text = (cents / 100).toString() + "." + (cents % 100).toString().padStart(2, '0')
return if (withCode) text + " " + currency else text
}
// inline: the lambda is copied into the call site, so return works inside it.
inline fun <T> retry(times: Int, block: (attempt: Int) -> T): T {
var last: Exception? = null
repeat(times) { attempt ->
try {
return block(attempt) // non-local return from retry
} catch (e: Exception) {
last = e // the lambda changes a local var of retry
}
}
throw last ?: IllegalStateException("times must be at least 1")
}
// A function interface can be created with a lambda.
fun interface OnItemClick {
fun onClick(id: Long)
}
fun main() {
println(formatPrice(1999)) // 19.99 USD
println(formatPrice(500, withCode = false)) // 5.00
val result = retry(3) { attempt ->
if (attempt < 2) error("fail " + attempt) else "ok on " + attempt
}
println(result) // ok on 2
val listener = OnItemClick { id -> println("clicked " + id) }
listener.onClick(7)
}Run the main ideas, plus the return trap and a closure, in plain Kotlin.
inline fun <T> retry(times: Int, block: (attempt: Int) -> T): T {
var last: Exception? = null
repeat(times) { attempt ->
try {
return block(attempt)
} catch (e: Exception) {
last = e
}
}
throw last ?: IllegalStateException("times must be at least 1")
}
fun firstNegative(items: List<Int>): String {
items.forEach { if (it < 0) return "stopped at " + it } // leaves firstNegative
return "all fine"
}
fun countNonNegative(items: List<Int>): Int {
var n = 0
items.forEach {
if (it < 0) return@forEach // leaves only this lambda call
n++
}
return n
}
fun makeCounter(): () -> Int {
var c = 0
return { c++ } // the lambda keeps c alive
}
fun main() {
println(retry(3) { attempt ->
if (attempt < 2) throw RuntimeException("fail " + attempt) else "ok on " + attempt
})
println(firstNegative(listOf(1, -2, 3))) // stopped at -2
println(countNonNegative(listOf(1, -2, 3))) // 2
val next = makeCounter()
println(next()) // 0
println(next()) // 1
}In production
- Users say some photos never upload. Only the first part of their gallery appears on the server.
- The upload loop used
photos.forEach { if (it.isCorrupt) return; upload(it) }. The developer meant "skip this one". - Cause:
forEachisinline, soreturnleaves the whole function. Every photo after the first corrupt one was skipped, with no error.
- Reproduce with a unit test. Pass a list where the second item is corrupt and assert that the third is still uploaded. The test fails before the fix.
- Use
return@forEach, or better, filter first:photos.filterNot { it.isCorrupt }.forEach { upload(it) }. - Report the skipped items so the user is not left guessing.
- Search the code base for
returninsideforEach,mapandletblocks.
- Memory grows as users move around the app. After many visits to one screen the app can run out of memory.
- Heap analysis (LeakCanary or the Android Studio profiler) shows old Activity instances held by a singleton's list of listeners.
- Cause: the screen registered
tracker.addListener { updateUi() }. The lambda uses a method of the Activity, so it holds the Activity. The singleton lives as long as the process and never removed the listener.
- Remove the listener when the screen stops, or use a lifecycle-aware API so removal is automatic.
- Do not pass Activity references to long-lived objects. If a context is needed, use the application context.
- Add LeakCanary to debug builds so the next leak is reported on the developer's device.
Common mistakes
- Using bare
returnin a lambda to mean "continue". In an inline lambda it leaves the function. Usereturn@forEachor filter first. - Making large functions
inline. The body is copied at every call site. Inline small functions that take lambdas. - Capturing an Activity or View in a long-lived lambda. Singletons, callbacks and static fields keep it alive.
- Nested lambdas that all use
it. The inner one hides the outer. Give names:{ user -> ... }. - Forgetting
@JvmOverloadson custom View constructors. XML inflation then fails with a missing constructor error. - Long lambda bodies inline in a call. Move the logic to a named function and pass it, so it can be tested.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“What is a higher-order function, and what is a closure?”
“What does return do inside a lambda?”
“Explain inline, noinline and crossinline.”
“How do default arguments work, and what can go wrong?”
Quiz
Inside fun f(), you write items.forEach with a lambda that contains a bare return. What happens when it runs?
Which is the function type for a function that takes an Int and returns a String?
What does the inline modifier do?
A singleton stores a lambda that calls a method of your Activity. What is the risk?
0 of 4 answered
Mini task
In the Playground, or a Kotlin file, do this in 15 minutes:
- Write
fun uploadAll(items: List<String>, onSkip: (String) -> Unit): Int. It returns how many items were "uploaded". An item that is blank is skipped and reported toonSkip. - First write it with a non-local
return countinsideforEachfor the blank case. (A barereturndoes not compile here, because the function returnsInt.) Call it withlistOf("a", "", "c")and note the result. - Fix it with
return@forEach. Confirm the result is 2 andonSkipwas called once. - Add a
makeCounter()like the one above, call it twice, and explain why the second call prints 1.
You are done when you can explain, without looking, why the first version returned the wrong count and why the fix works.