inline
- Kotlin course
- Expert
- Lesson 39/47
- 5 min
Learn function call optimization with inline.
What is inline?
inline is the keyword that embeds a function body directly at the call site instead of making a call. It avoids call overhead and lambda allocation.
Example: inline fun measure(block: () -> Unit) { block() }. Normally block is allocated as an object; with inline the body is placed directly and no object is created. This is especially useful for higher-order functions. Overuse grows method size; it is used on hot paths.
inline and lambdas
inline removes lambda allocation in higher-order functions. The lambda body is placed directly at the call site.
Example: inline fun doubleIt(x: Int): Int = x * 2. The call doubleIt(5) turns into 5 * 2 after compilation. This zeroes call cost in hot loops. The reified type parameter is also only allowed in inline functions; it gives runtime type access.
Practice Write doubleIt
Define inline fun doubleIt(x: Int): Int. It should return x * 2. In main, write println(doubleIt(5)).
Starter code
// add the doubleIt function
fun main() {
// print the doubleIt(5) result
}Sample solution
inline fun doubleIt(x: Int): Int = x * 2
fun main() {
println(doubleIt(5))
}Expected output
10
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the inline parts
| Term | Meaning |
|---|---|
inline |
Embeds the call |
call site |
Call location |
lambda |
Helper function |
overhead |
Call cost |
2 What does inline prevent most?
inline is most useful with lambdas.- Lambda allocation and call cost Correct answer
- Class loading
- Disk I/O
- Memory leaks
Explanation: inline prevents lambda allocation and call cost.
3 Complete the inline declaration
____ fun measure(block: () -> Unit) { block() }
inline fun measure(block: () -> Unit) { block() }
Explanation: inline fun measure embeds the body at the call site.