Question #377MediumNative Android

Explain inline functions and when to use them in Java/Kotlin?

#kotlin#inline-functions#performance

Answer

Overview

Inline functions copy function code to call sites, eliminating function call overhead.


Kotlin Inline Functions

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

// Usage
measureTime {
    // Code here is inlined at call site
}

When to Use

1. Higher-Order Functions

kotlin
inline fun <T> List<T>.customFilter(predicate: (T) -> Boolean): List<T> {
    val result = mutableListOf<T>()
    for (item in this) {
        if (predicate(item)) result.add(item)
    }
    return result
}

2. Reified Type Parameters

kotlin
inline fun <reified T> isInstanceOf(value: Any): Boolean {
    return value is T
}

// Usage
if (isInstanceOf<String>(obj)) { }

noinline

kotlin
inline fun foo(
    inlined: () -> Unit,
    noinline notInlined: () -> Unit
) {
    inlined()
    notInlined()
}

crossinline

kotlin
inline fun runAsync(crossinline block: () -> Unit) {
    thread {
        block() // Can be called from another context
    }
}

Java

Java doesn't have explicit inline. JVM does automatic inlining based on heuristics.

java
// JVM may inline small methods automatically
private int add(int a, int b) {
    return a + b;
}

Performance Impact

kotlin
// Without inline - function call overhead
fun repeat(times: Int, action: () -> Unit) {
    for (i in 0 until times) action()
}

// With inline - no overhead
inline fun repeat(times: Int, action: () -> Unit) {
    for (i in 0 until times) action()
}

Caution: Don't overuse. Only inline small functions with lambda parameters.