Mastering Kotlin Inline Functions: A Deep Dive into inline, noinline, and crossinline
In Kotlin, inline, crossinline, and noinline are keywords used when working with higher-order
functions (functions that take other functions as parameters or return functions).
1. inline
The inline
keyword is used to request the compiler to inline the function body, meaning the compiler replaces the function call with its actual body at the call site. This is particularly useful for higher-order functions to reduce the overhead of creating function objects and performing lambda calls.
Use Case
- Reduces runtime overhead caused by lambda expressions and function calls.
- Particularly useful in performance-critical applications.
Example:
Compiled Output: The lambda is directly inlined into the inlineFunction
‘s call site:
2. noinline
The noinline
keyword is used to prevent inlining for specific lambda parameters in an inline
function. Normally, all lambda parameters in an inline
function are inlined, but with noinline
, you can exclude certain lambdas.
Use Case
- Useful when you need to pass the lambda as a first-class object (e.g., to store or pass it elsewhere), which cannot happen if it’s inlined.
Example:
Here, the action
lambda is not inlined and can be treated like a normal function object.
3. crossinline
The crossinline
keyword is used to mark a lambda parameter in an inline
function that must not return (i.e., it can’t use return
to exit the enclosing function). This is often required when the lambda is passed to another function or stored.
Use Case
- Ensures the lambda can’t cause unexpected behavior by returning from the enclosing function.
Example:
If you attempt to use return
inside the lambda, the compiler will throw an error because the lambda is passed to another context (in this case, a Runnable
).
Summary of Differences
Keyword | Behavior | Use Case |
---|---|---|
inline |
Inlines the function body and lambdas at the call site. | Reduce runtime overhead for high-performance or frequently called functions. |
noinline |
Prevents specific lambda parameters from being inlined in an inline function. |
When you need to pass or store lambda parameters as objects. |
crossinline |
Prohibits non-local returns (return from the outer function) inside the lambda parameter. |
When lambdas are passed to other contexts or threads, ensuring safe and predictable behavior. |