0
0
KotlinConceptBeginner · 3 min read

What is Inline Function in Kotlin: Explanation and Example

An 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.

kotlin
inline fun repeatTwice(action: () -> Unit) {
    action()
    action()
}

fun main() {
    repeatTwice { println("Hello from inline function!") }
}
Output
Hello from inline function! 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.

Key Takeaways

Inline functions copy their code at call sites to reduce function call overhead.
They are especially useful when functions take lambda parameters.
Use inline functions for small, frequently used utility functions.
Avoid inlining large functions to prevent code bloat.
Inlining improves runtime performance but may increase compile time slightly.