Sobes.tech
Junior

What are inline functions?

sobes.tech AI

Answer from AI

Inline functions are functions that the compiler inline directly into the call site in the compiled binary, instead of generating a standard function call.

Advantages:

  • Performance: Reduces overhead of function calls (argument passing, stack management).
  • Less boilerplate: Often used for higher-order functions, avoiding creation of anonymous classes or objects for functional interfaces.

Disadvantages:

  • Code size: If an inline function is large or called frequently, it can significantly increase the code size.
  • Compatibility: Not all functions can be inlined (e.g., recursive functions, functions containing try/catch/finally).

In Kotlin, inline functions are declared with the inline keyword:

// Declaration of an inline function with a lambda parameter
inline fun performAction(block: () -> Unit) {
    // Inline code will be here
    block() // Lambda will also be inlined
}

// Usage of inline function
performAction {
    // Action
}

Inlining lambdas in Kotlin allows using return from the calling function inside the lambda, called non-local return:

// Example of non-local return
inline fun executeConditional(condition: Boolean, block: () -> Unit) {
    if (condition) {
        block()
    }
    // Code after lambda call
}

fun someFunction() {
    executeConditional(true) {
        // If condition is true, this return will exit someFunction
        return
    }
    // This code will not execute if condition was true
}