Junior — Middle
What does the 'noinline' modifier do for functions in Kotlin and what is its use?
sobes.tech AI
Answer from AI
In Kotlin, the noinline modifier is used in the context of inline functions that accept lambda expressions as parameters. By default, all lambdas in inline functions are also inlined (embedded into the calling function's code), which improves performance.
However, sometimes it is necessary to prevent a specific lambda from being inlined, for example, if the lambda is passed further or used as an object. For this, the lambda parameter is marked with the noinline modifier.
Example:
inline fun doSomething(inlineLambda: () -> Unit, noinline noInlineLambda: () -> Unit) {
inlineLambda() // will be inlined
noInlineLambda() // will not be inlined
}
Using noinline allows controlling which lambdas are inlined and which are not, which is important for code correctness and optimization.