0
0
KotlinHow-ToBeginner · 3 min read

How to Use Inline Function in Kotlin: Syntax and Examples

In Kotlin, you use inline before a function declaration to suggest the compiler to inline the function's bytecode at call sites, improving performance especially with lambdas. This is done by writing inline fun functionName() { }.
📐

Syntax

An inline function in Kotlin is declared by adding the inline keyword before the fun keyword. This tells the compiler to replace calls to this function with the actual function code during compilation.

  • inline: Keyword to mark the function for inlining.
  • fun: Declares a function.
  • functionName: The name of the function.
  • parameters: Input parameters for the function.
  • function body: The code that runs when the function is called.
kotlin
inline fun greet(name: String) {
    println("Hello, $name!")
}
💻

Example

This example shows an inline function measureTime that takes a lambda and prints the time it took to run. The inline keyword helps avoid creating extra objects for the lambda, making the code faster.

kotlin
inline fun measureTime(block: () -> Unit) {
    val start = System.currentTimeMillis()
    block()
    val end = System.currentTimeMillis()
    println("Time taken: ${end - start} ms")
}

fun main() {
    measureTime {
        for (i in 1..5) {
            println(i)
        }
    }
}
Output
1 2 3 4 5 Time taken: X ms
⚠️

Common Pitfalls

One common mistake is using inline unnecessarily on large functions, which can increase the final code size. Also, inline functions cannot be recursive because inlining would cause infinite expansion. Another pitfall is forgetting that inline only affects functions with lambda parameters effectively.

kotlin
/* Wrong: Large function marked inline can bloat code */
inline fun bigFunction() {
    // Imagine many lines of code here
    println("This is a big function")
}

/* Right: Use inline for small functions with lambdas */
inline fun smallInline(block: () -> Unit) {
    block()
}
📊

Quick Reference

KeywordDescription
inlineMarks a function to be inlined at call sites
funDeclares a function
lambda parameterFunctions with lambda parameters benefit most from inlining
no recursionInline functions cannot call themselves recursively
performanceInlining reduces overhead of lambda calls

Key Takeaways

Use inline before fun to create an inline function in Kotlin.
Inlining improves performance by replacing function calls with the function code, especially for lambdas.
Avoid marking large functions as inline to prevent code size increase.
Inline functions cannot be recursive.
Use inline functions mainly when passing lambdas to reduce runtime overhead.