-
Notifications
You must be signed in to change notification settings - Fork 23
noinline
In Kotlin, the noinline
keyword is used as an annotation on a function parameter of a higher-order function to specify that the corresponding lambda expression passed to that parameter should not be allowed to be inlined by the compiler.
When a function is marked with the inline
modifier, the compiler may choose to inline the function's code at the call site, eliminating the overhead of a function call. However, when you pass a lambda expression as a parameter to an inline function, the compiler may also attempt to inline the lambda code at the call site. In some cases, you may want to prevent the inlining of a particular lambda expression, and that's where noinline
comes in.
Here's an example to illustrate its usage:
inline fun executeWithLogging(action: () -> Unit, noinline loggingAction: () -> Unit) {
println("Executing action")
action()
println("Action executed")
println("Logging action")
loggingAction()
println("Action logged")
}
fun main() {
executeWithLogging(
{
// This code will be inlined
println("Performing some action")
},
{
// This code will NOT be inlined, thanks to 'noinline'
println("Logging the action")
}
)
}
In this example, the executeWithLogging
function is marked as inline
, allowing the compiler to inline the lambda passed to the action
parameter. The lambda passed to the loggingAction
parameter, on the other hand, is marked with noinline
, indicating that it should not be inlined even though the containing function is marked as inline
.