What is Inline Function in Kotlin: Explanation and Example
inline function in Kotlin is a special function where the compiler replaces the function call with the actual function code during compilation. This helps reduce the overhead of function calls, especially for small functions or those using lambda parameters.How It Works
Imagine you have a small task you want to repeat many times. Normally, you would call a function each time, which means the program jumps to that function and then comes back. This jumping takes some time. An inline function tells Kotlin to copy the function's code directly where it is called, like pasting the task steps instead of jumping to a separate place.
This is especially useful when your function takes other functions (called lambdas) as arguments. By inlining, Kotlin avoids creating extra objects and function calls, making your program faster and more efficient.
Example
This example shows an inline function that takes a lambda and runs it twice.
inline fun repeatTwice(action: () -> Unit) {
action()
action()
}
fun main() {
repeatTwice { println("Hello from inline function!") }
}When to Use
Use inline functions when you want to improve performance by avoiding the cost of function calls, especially for small functions or those that take lambdas. They are great for utility functions like repeatTwice, filter, or map where lambdas are common.
However, avoid inlining very large functions because copying big code everywhere can increase your app size and slow down compilation.
Key Points
- Inline functions replace calls with code to reduce overhead.
- They improve performance when using lambdas.
- Best for small, frequently called functions.
- Avoid inlining large functions to keep code size small.