Kotlin Inline Functions
An inline function has its body copied into each place that calls it. The lambda passed to it is copied along with the body.
An inline function at work
announce prints a start line, runs its lambda, and prints an end line. The three prints land in order.
inline fun announce(action: () -> Unit) {
println("Starting")
action()
println("Finished")
}
fun main() {
announce {
println("Working")
}
}A non-local return
The return inside the lambda leaves main itself, not just the lambda. The last line of main never prints, and the search stops at tree.
inline fun findFirst(words: List<String>, action: (String) -> Unit) {
for (word in words) {
action(word)
}
}
fun main() {
val words = listOf("ant", "tree", "bee")
findFirst(words) { word ->
println("Checking " + word)
if (word.startsWith("t")) {
println("Found " + word)
return
}
}
println("Search over")
}Storing a lambda with noinline
The second parameter is marked noinline, so the body can store it in a variable. The stored value runs after the first lambda.
inline fun runBoth(first: () -> Unit, noinline second: () -> Unit) {
first()
val stored: () -> Unit = second
stored()
}
fun main() {
runBoth({ println("First run") }, { println("Second run") })
}Example
inline fun runLines(times: Int, action: (Int) -> Unit) {
for (i in 1..times) {
action(i)
}
}
fun main() {
runLines(3) { println("Line " + it) }
println("All lines shown")
}Key points
- Write inline before fun to mark a function as inline.
- The compiler places the body at the call site instead of making a normal call.
- Inlining a lambda avoids building a separate function object for it.
- A return inside an inline lambda returns from the enclosing function.
- That early exit is called a non-local return.
- Mark a parameter noinline when that lambda must be stored as a value.
In this example, runLines is inline and takes a count plus a lambda. The lambda prints one line for each number from 1 to 3. The final print runs after the loop ends, because this lambda has no return inside it.
Note
Inline fits small functions that take a lambda and run it right away.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Kotlin Playground
Exercise
What does a return inside an inline lambda do?