0
0
KotlinConceptBeginner · 3 min read

What is noinline in Kotlin: Explanation and Examples

In Kotlin, noinline is a keyword used to mark a lambda parameter in an inline function that should not be inlined. It tells the compiler to keep the lambda as a normal object instead of inserting its code directly, allowing more flexibility in how the lambda is used.
⚙️

How It Works

When you mark a function as inline in Kotlin, the compiler tries to replace calls to that function with the actual code inside it. This helps improve performance by avoiding function call overhead. However, sometimes you want to inline the function but keep some lambda parameters as regular objects. That's where noinline comes in.

Think of it like a recipe book: inlining is like copying the recipe directly into your cooking plan, so you don't have to flip pages. But if a recipe is marked noinline, you keep it as a separate card you refer to, instead of copying it. This allows you to pass that lambda around or store it, which is not possible if it is fully inlined.

💻

Example

This example shows an inline function with two lambda parameters. One is inlined, and the other is marked noinline so it is not inlined.

kotlin
inline fun doWork(inlineLambda: () -> Unit, noinline noinlineLambda: () -> Unit) {
    println("Start work")
    inlineLambda()  // This lambda is inlined
    noinlineLambda() // This lambda is not inlined
    println("End work")
}

fun main() {
    doWork(
        inlineLambda = { println("Inline lambda called") },
        noinlineLambda = { println("Noinline lambda called") }
    )
}
Output
Start work Inline lambda called Noinline lambda called End work
🎯

When to Use

Use noinline when you want to inline a function for performance but need to keep some lambda parameters as objects. This is useful if you want to:

  • Store the lambda in a variable
  • Pass the lambda to another function
  • Use the lambda multiple times or asynchronously

For example, if you want to pass a lambda to a thread or save it for later, noinline prevents the compiler from inlining it, allowing these operations.

Key Points

  • noinline applies only to lambda parameters in inline functions.
  • It prevents the lambda from being inlined, keeping it as a normal object.
  • This allows storing or passing the lambda around.
  • Use it to balance performance and flexibility.

Key Takeaways

noinline marks lambda parameters in inline functions to avoid inlining them.
It allows lambdas to be stored, passed, or used multiple times.
Use noinline when you need flexibility with lambdas inside inline functions.
Inlining improves performance but noinline gives control over specific lambdas.