Sobes.tech
Junior — Middle

Can you explain what a function with crossinline in Kotlin is and how it differs from regular inline functions?

sobes.tech AI

Answer from AI

In Kotlin, the inline keyword is used for functions to compile their code directly into the call sites, reducing call overhead and enabling features like non-local returns and reified types.

The crossinline parameter is used for lambda expressions passed to inline functions to prevent the use of non-local return from that lambda.

Differences:

  • A regular inline function allows lambdas without crossinline to use non-local return, i.e., to exit the outer function.
  • If a lambda parameter is marked as crossinline, it cannot use non-local return, which prevents exiting the outer function.

This is useful when the lambda is called not directly, for example, inside another lambda or asynchronously, where non-local return is not possible or undesirable.

Example:

inline fun foo(crossinline block: () -> Unit) {
    val runnable = Runnable {
        block() // non-local return is forbidden due to crossinline
    }
    runnable.run()
}

fun main() {
    foo {
        println("Inside crossinline lambda")
        // return // Error: non-local return is forbidden
    }
    println("After foo")
}

Thus, crossinline guarantees that the lambda cannot break out of the outer function with a non-local return, which is important for correctness and safety.