WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Kotlin · Basic · question 18 of 100

What are inline functions in Kotlin, and when should you use them?

📕 Buy this interview preparation book: 100 Kotlin questions & answers — PDF + EPUB for $5

In Kotlin, ‘inline‘ functions are a way to optimize your code by eliminating the overhead of function calls. When a function is marked as ‘inline‘, the compiler replaces the function call with the actual code of the function at the call site. This can improve performance by reducing the overhead of function calls, especially when the function is called frequently or from within a loop.

Here’s an example of how an inline function can be used:

inline fun measureTimeMillis(block: () -> Unit): Long {
    val startTime = System.currentTimeMillis()
    block()
    return System.currentTimeMillis() - startTime
}

fun main() {
    val time = measureTimeMillis {
        // some code that needs to be timed
    }
    println("Time: $time ms")
}

In this example, the ‘measureTimeMillis‘ function is marked as ‘inline‘. When it’s called in the ‘main‘ function, the compiler replaces the call with the actual code of the function, like this:

fun main() {
    val startTime = System.currentTimeMillis()
    // some code that needs to be timed
    val time = System.currentTimeMillis() - startTime
    println("Time: $time ms")
}

This can result in faster performance, especially if ‘measureTimeMillis‘ is called multiple times or from within a loop.

However, not all functions should be marked as ‘inline‘. Here are a few things to keep in mind:

- The ‘inline‘ keyword increases the size of the compiled code. This can be problematic for large functions or when called frequently, as it can lead to larger binary size and more memory consumption.

- Functions that have high complexity or perform heavy computations may not be good candidates for inlining, as they may cause performance issues due to code bloat.

- Functions that are recursive or have nested functions cannot be made ‘inline‘.

In general, ‘inline‘ functions should be used sparingly and only for functions that are called frequently or from within a loop, where the performance benefits outweigh the potential drawbacks.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Kotlin interview — then scores it.
📞 Practice Kotlin — free 15 min
📕 Buy this interview preparation book: 100 Kotlin questions & answers — PDF + EPUB for $5

All 100 Kotlin questions · All topics