Sobes.tech
Junior — Middle

For what purposes are inline functions used and how do they differ from regular functions?

sobes.tech AI

Answer from AI

Inline functions in Kotlin (often used in Android development) are used to optimize performance. They allow the compiler to insert the body of the function directly at the call site, reducing the overhead of function calls (such as creating a call stack). This is especially useful for higher-order functions that accept lambda expressions.

Differences from regular functions:

  • Regular functions are called through the call stack, which adds a small overhead.
  • Inline functions are compiled so that their body is substituted at the call site, speeding up execution.

Example:

inline fun measureTime(block: () -> Unit) {
    val start = System.currentTimeMillis()
    block()
    val end = System.currentTimeMillis()
    println("Execution time: ${end - start} ms")
}

// Usage
measureTime {
    // some code
}

Here, the lambda block does not create an additional object because the function is inline.