Middle+
Why is the `crossinline` modifier used in Kotlin?
sobes.tech AI
Answer from AI
The crossinline modifier is used to mark lambda parameters of inline functions.
It indicates to the compiler that the corresponding lambda function cannot perform a non-local return, meaning it cannot use the return operator to exit from the outer function. However, the lambda can still be inlined at the call site.
Example:
// Regular inline function with a non-local return
inline fun runTask(task: () -> Unit) {
task() // Non-local return is possible from task()
println("Task finished")
}
// Inline function with a crossinline parameter
inline fun runSafeTask(crossinline task: () -> Unit) {
// try-finally block as an example where crossinline is needed
try {
task() // Cannot perform a non-local return from task()
} finally {
println("Cleanup")
}
println("Safe task finished")
}
fun main() {
// Using runTask
runTask {
println("Inside runTask lambda")
return // Allowed: non-local return from main()
}
// The print "Task finished" will NOT be executed
// Using runSafeTask
runSafeTask {
println("Inside runSafeTask lambda")
// return // Compile error: non-local return is forbidden
}
println("After safe task") // This print will be executed
}
When is this useful:
- When you need to ensure that code after the call to a
crossinlinelambda will be executed (for example, intry-finallyblocks). - When a lambda is passed as an argument to another function that may not be inlined, and you want to prevent a non-local return that could disrupt the flow of execution.