Inline functions
- Kotlin course
- Expert
- Lesson 2/47
- 5 min
Learn performance safety with inline and noinline.
What does inline do?
The inline keyword tells the compiler to copy a function body into its call site. This reduces the lambda allocation overhead in higher-order functions.
Example: inline fun forEachTwice(items: List<Int>, action: (Int) -> Unit). Here the action lambda is not allocated each call; it is inlined into the body. This improves performance but grows the bytecode. For long bodies, avoid inline. It is ideal for short, lambda-parameter functions.
noinline and crossinline
Sometimes you do not want a lambda parameter to be inlined. Then use the noinline marker: noinline action: () -> Unit.
Sometimes an inlined lambda does a non-local return, which is a problem in some contexts. Use crossinline to prevent it. Example: when passing a lambda to another function inside an inline function, use crossinline. Both keywords only apply to parameters of inline functions.
Practice Write inline forEachTwice
Define inline fun forEachTwice(items: List<Int>, action: (Int) -> Unit). It should call action twice for each item. In main, call it with listOf(1, 2) and use println(it) as the action.
Starter code
// add the keyword
fun forEachTwice(items: List<Int>, action: (Int) -> Unit) {
for (i in items) {
// call action twice
}
}
fun main() {
forEachTwice(listOf(1, 2)) { /* print the item */ }
}Sample solution
inline fun forEachTwice(items: List<Int>, action: (Int) -> Unit) {
for (i in items) {
action(i)
action(i)
}
}
fun main() {
forEachTwice(listOf(1, 2)) { println(it) }
}Expected output
1 1 2 2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Add the inline keyword
____ fun twice(action: () -> Unit) {
action()
action()
}
inline fun twice(action: () -> Unit) {
action()
action()
}
Explanation: inline optimizes lambda-parameter functions.
2 Match inline keywords
| Term | Meaning |
|---|---|
inline |
Copies the body |
noinline |
Do not copy parameter |
crossinline |
Blocks local return |
fun |
Function declaration |
3 When is an inline function preferred?
- For short, lambda-parameter, frequently called functions Correct answer
- Only for abstract class methods
- For long, rarely called functions
- Only for non-inlineable generic functions
Explanation: inline shines for short, frequently called lambda-parameter functions.