CodeBlanks Logo Icon CodeBlanks

inline

Learn performance optimization with inline.

inline

The inline keyword makes a function be inlined directly at the call site. It reduces the lambda creation overhead in higher-order functions.

Example: inline fun repeatN(times: Int, action: (Int) -> Unit) { for (i in 1..times) action(i) }. Calling repeatN(3) { println("Run $it") } prints three times. Thanks to inline, no lambda object is created; the code is inlined at the call site. This helps performance. But each inline function can grow code size; it is used for small functions.

The repeatN function

An inline higher-order function inlines the lambda at the call site. The action(i) call is expanded at compile time.

Example: inline fun repeatN(times: Int, action: (Int) -> Unit) { for (i in 1..times) action(i) }. Calling repeatN(3) { println("Run $it") } prints Run 1 Run 2 Run 3. it is the lambda's single parameter. inline functions are common in collection methods; forEach, map and filter are inline in the standard library.

Practice The repeatN inline function

Define inline fun repeatN(times: Int, action: (Int) -> Unit) whose body does for (i in 1..times) action(i). In main call repeatN(3) { println("Run $it") }.

Starter code

Main.kt
// Define the repeatN inline function
// takes times and action, iterates with for
// call it three times in main

Sample solution

Main.kt
inline fun repeatN(times: Int, action: (Int) -> Unit) {
    for (i in 1..times) action(i)
}

fun main() {
    repeatN(3) { println("Run $it") }
}

Expected output

Run 1
Run 2
Run 3

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does the <code>inline</code> keyword provide?

  • Hiding the function
  • Pinning the function
  • Recursion of the function
  • Inlining the function body at the call site Correct answer

Explanation: inline inlines the function body at the call site.

2 Match the inline parts

Term Meaning
inline fun repeatN inline signature
action: (Int) -> Unit Function parameter
for (i in 1..times) Loop
action(i) Lambda call

3 Complete the inline function definition

Question
inline ____ repeatN(times: Int, action: (Int) -> Unit) {
    for (i in 1..times) action(i)
}
Answer
inline fun repeatN(times: Int, action: (Int) -> Unit) {
    for (i in 1..times) action(i)
}

Explanation: It is written as inline fun repeatN.

All lessons in Intermediate