0
0
KotlinConceptIntermediate · 3 min read

What is crossinline in Kotlin: Explanation and Example

In Kotlin, crossinline is a modifier used on lambda parameters to prevent non-local returns from that lambda. It ensures the lambda cannot use return to exit from the outer function, which is useful when the lambda is called in a different context like another thread or inline function.
⚙️

How It Works

Imagine you have a function that takes a block of code (a lambda) and runs it. Normally, if the lambda uses return, it can exit not only the lambda but also the whole function that called it. This is called a non-local return.

However, sometimes the lambda is passed to another place where such a return would be unsafe or confusing, like when the lambda runs later or in a different thread. To stop this, Kotlin lets you mark the lambda parameter with crossinline. This means the lambda cannot use return to jump out of the outer function; it can only return from itself.

Think of it like telling the lambda: "You can finish your job, but you can't stop the whole process early." This helps keep the program flow clear and safe.

💻

Example

This example shows a function with a crossinline lambda parameter. The lambda tries to use return, but it can only return from itself, not the outer function.

kotlin
inline fun runCrossinline(block: crossinline () -> Unit) {
    val runnable = Runnable {
        block() // Lambda called inside another context
    }
    runnable.run()
}

fun test() {
    runCrossinline {
        println("Inside lambda")
        // return // This would cause a compile error because of crossinline
    }
    println("After lambda")
}

fun main() {
    test()
}
Output
Inside lambda After lambda
🎯

When to Use

Use crossinline when you have an inline function that takes a lambda, and that lambda is called not directly but inside another function or thread, like a Runnable or callback. This prevents the lambda from using return to exit the outer function, which would be unsafe or impossible in that context.

For example, if you pass a lambda to a background thread or a delayed callback, mark it crossinline to avoid confusing control flow and compiler errors.

Key Points

  • crossinline prevents non-local returns from lambdas.
  • It is used in inline functions when lambdas are called in other contexts.
  • It keeps program flow safe and clear by disallowing return from the outer function inside the lambda.
  • Without crossinline, lambdas can use return to exit the outer function.

Key Takeaways

crossinline stops lambdas from using return to exit the outer function.
Use crossinline when lambdas run in different contexts like threads or callbacks.
It helps avoid confusing control flow and compiler errors.
Without crossinline, lambdas can perform non-local returns.
It is a modifier for inline function lambda parameters.