Middle+
What is the purpose of the keyword crossinline in Kotlin?
sobes.tech AI
Answer from AI
crossinline is used in Kotlin to mark function parameters in inline functions. It allows calling such lambda parameters inside nested functions (such as anonymous class objects) that are not inline.
Regular lambdas in inline functions can contain non-local returns (returns that exit from the outer function). A lambda marked with crossinline cannot contain non-local returns.
Main purposes:
- To allow using a lambda in contexts where the default inline lambda (which allows non-local returns) cannot be used (e.g., anonymous objects, local functions).
- To prevent non-local returns from the lambda when it is undesirable or impossible due to the code structure (e.g., when passing a lambda to another thread).
Example:
inline fun runAsyncAndFinish(crossinline block: () -> Unit) {
// Creating an anonymous Runnable object
val runnable = object : Runnable {
override fun run() {
block() // Using crossinline lambda inside
// here block() cannot perform a non-local return from runAsyncAndFinish
}
}
// Running in a separate thread (example)
Thread(runnable).start()
// if block was not crossinline, block() could do a return from runAsyncAndFinish
// which is impossible from a thread other than the caller
}
fun testCrossinline() {
println("Before runAsyncAndFinish")
runAsyncAndFinish {
println("Inside async block")
// return // Compilation error: cannot use a non-local return with crossinline
}
println("After runAsyncAndFinish")
}