Junior — Middle
How are inline functions implemented in Kotlin and how does this affect performance and code structure?
sobes.tech AI
Answer from AI
In Kotlin, functions with the inline keyword are compiled so that their body is inserted directly at the call site, rather than being called as a separate function. This reduces the overhead of function calls, which is especially useful for higher-order functions (accepting lambdas).
Advantages:
- Improved performance by eliminating function call overhead.
- Allows the use of
non-local returnsandreifiedtypes in lambdas.
Example:
inline fun measureTime(block: () -> Unit) {
val start = System.currentTimeMillis()
block()
println("Time: ${System.currentTimeMillis() - start} ms")
}
fun main() {
measureTime {
println("Executing code")
}
}
However, excessive use of inline functions can increase the bytecode size, so they should be used thoughtfully.