Senior
What is the purpose of the inline modifier in Kotlin?
sobes.tech AI
Answer from AI
The inline modifier in Kotlin is used for functions so that the compiler inserts the function body directly at the call site instead of a regular call by reference. This helps avoid the overhead of function calls, especially useful for higher-order functions that accept lambda expressions.
Advantages of inline:
- Reduces the cost of function calls.
- Allows
non-local returnsfrom lambdas. - Enables the use of reified types in generics.
Example:
inline fun measureTime(block: () -> Unit) {
val start = System.currentTimeMillis()
block()
println("Time: ${System.currentTimeMillis() - start} ms")
}
fun main() {
measureTime {
// code to measure time
}
}
Here, measureTime will be inlined at the call site, which increases performance.