Skip to content

Crossline modifier

Devrath edited this page Feb 15, 2024 · 1 revision

In Kotlin, the crossinline modifier is used in the context of inline functions and is applied to function parameters. It is used to restrict the usage of non-local control flow, such as return, within the lambda expressions passed to the inline function.

When you mark a lambda parameter with the crossinline modifier, you're telling the compiler that the lambda cannot have non-local control flow, which means it cannot contain a return statement that would return control to the calling function.

Here's a simple example to illustrate the use of crossinline:

inline fun executeInContext(crossinline action: () -> Unit) {
    // Some inline function logic
    action()
    // More inline function logic
}

fun main() {
    executeInContext {
        // This is valid
        println("Executing in context")
        
        // This is not allowed if the parameter is marked with crossinline
        // return@executeInContext
    }
}

In the example above, executeInContext is an inline function that takes a lambda expression as a parameter. By using crossinline, you ensure that the lambda expression passed to action cannot use the return statement to return control flow to the calling function (executeInContext in this case). This is useful when the inline function relies on the lambda to be executed within a specific context, and introducing non-local control flow could break that context.

Note that without crossinline, the lambda expression can use return to exit both the lambda and the calling function, which may lead to unexpected behavior in certain cases.

inline fun executeInContext(action: () -> Unit) {
    // Some inline function logic
    action()
    // More inline function logic
}

fun main() {
    executeInContext {
        // This is valid, but it will also exit the calling function
        return@executeInContext
    }
}
Clone this wiki locally