Sobes.tech
Junior — Middle

In which cases is it recommended to use the inline function?

sobes.tech AI

Answer from AI

The inline function in Kotlin is recommended for small functions that are called frequently, especially if they take lambda expressions as parameters. This allows the compiler to insert the function body directly at the call site, reducing call overhead and potentially improving performance.

Use inline when:

  • The function is short and called often.
  • The function takes lambdas to avoid creating additional objects and calls.
  • You need to reduce call overhead in performance-critical places.

Example:

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

// Usage
measureTime {
    // code whose execution time needs to be measured
}