Middle
What is an 'inline' function in Kotlin and in which cases should it be used?
sobes.tech AI
Answer from AI
An inline function in Kotlin is a function whose bytecode is inserted directly at the call site during compilation, instead of creating a separate function call.
The advantage of inline is that it helps avoid the overhead associated with calling a regular function (creating a stack frame, passing arguments, jumping to the function code, returning). This is especially useful for high-order functions that accept lambdas.
Use cases include:
- When the function is high-order and accepts lambdas: it prevents creating unnecessary objects for lambdas at runtime.
- For small functions, to reduce call overhead, especially if they are called very frequently.
- Reducing costs when using standard constructs that mimic control structures, for example:
// Example of an inline function with a lambda
inline fun performAction(action: () -> Unit) {
// Some actions before
action() // Lambda is inlined here
// Some actions after
}
// Usage:
fun main() {
performAction {
println("Action is being performed!") // This code will be inlined
}
}
Should not be used if:
- The function is large: inlining large code can increase the bytecode size and potentially lead to longer app startup times.
- The function is recursive: it can lead to infinite inlining and stack overflow.
- The function is called very rarely.
The noinline keyword can be used to prevent inlining of specific lambdas within an inline function:
inline fun executeTwoActions(action1: () -> Unit, noinline action2: () -> Unit) {
action1() // Will be inlined
action2() // Lambda object will be created
}