Sobes.tech
Junior — Middle

Kas saaksite selgitada inline funktsioonide kontseptsiooni Kotlinis ja nende eeliseid?

sobes.tech AI

Vastus AI-lt

In Kotlin, the inline keyword is used for functions so that the compiler, during compilation, inserts the body of the function directly at the call sites instead of a normal call by reference. This is especially useful for higher-order functions that accept lambda expressions.

Advantages of inline functions:

  • Reducing function call overhead. When using lambdas without inline, objects and additional calls are created, which reduces performance.
  • Performance improvement. Direct code insertion allows avoiding the creation of extra objects and calls.
  • Ability to use noinline and crossinline. This allows flexible management of lambda behavior inside inline functions.

Example:

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

fun main() {
    measureTime {
        // some code
        Thread.sleep(100)
    }
}

Here, measureTime is an inline function, and the lambda body will be inserted directly, reducing additional costs.