Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 134 ยท Functions

Inline Functions

Learn Kotlin inline functions - what inline does, non-local return, noinline and crossinline, reified type parameters, performance trade-offs and common compiler errors, with runnable code.

When you pass a lambda to an ordinary function, Kotlin has to create an object for it and call that object later. For map or filter on a short list nobody notices, but the cost adds up in hot loops and in functions that take lambdas all the time. The keyword inline tells the compiler: do not call this function, copy its body (and the lambda bodies you pass in) straight into the place where it is used. No function object, no extra call.

That is the performance story, and it is the less interesting half. Inlining also unlocks two language features that ordinary functions cannot offer: non-local return from inside a lambda, and reified type parameters that survive to run time. This lesson explains all three, plus the modifiers noinline and crossinline that appear as soon as you write inline functions yourself. It follows Higher-Order Functions and uses ideas from Lambdas.

What inline does

Here is a small inline function that runs a block and reports how many times it ran:

Kotlin Your first inline function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is hi, hi, count = 2. After compilation, main behaves as if you had written count++; count++; println("hi"); println("hi") by hand. There is no lambda object and no call to twice. You never see this in the source, but it explains everything else in this lesson: because the lambda's code ends up inside the caller, it can do things a separate function body could not.

You cannot see inlining in the output, only in the generated bytecode. For learning purposes, think of inline as "the compiler pastes the code in". It is a copy-paste done safely by the compiler, with argument evaluation order preserved.

The cost: code size

If an inline function is large and called from many places, each call site gets a full copy of the body, which makes the compiled program bigger. This is why the standard library marks small, lambda-taking functions as inline (map, filter, forEach, let, apply, repeat) but not big ones. The compiler even hints that inlining a function without function parameters is pointless:

Kotlin inline without a lambda

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The program prints 81; IDEs and kotlinc point out that inlining brings little here. Without a function parameter there is nothing to gain: the JVM's own optimizer already inlines tiny functions.

Rule of thumb: use inline for small higher-order functions, and for functions that need reified types. Do not sprinkle it on everything.

Non-local return

In an ordinary function, a lambda cannot use a bare return to leave the function that contains the lambda. Watch what happens with a normal higher-order function:

Kotlin return in a non-inline lambda (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler stops with main.kt:6:9: error: 'return' is prohibited here. The lambda may run any time later, even after main has finished, so returning from main makes no sense. Now make callIt inline and the same lambda is legal:

Kotlin Non-local return from an inline lambda

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is only inside. The return inside the lambda returns from main, because the lambda's code is part of main after inlining. In findFirstNegative, return it leaves the function as soon as a negative number is found, which is exactly what a for loop would do. That is why you can write forEach { if (...) return ... } in Kotlin without any tricks, and it works because forEach is inline.

If you only want to leave the lambda and continue with the code after the call, use a labeled return:

Kotlin return@label versus plain return

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

You get positive: 3, positive: 4, positive: 9, done with forEach, first big: 4. return@forEach behaves like continue; return@run it leaves the run block with a value, much like break with a result. Labels for loops and lambdas are covered in break, continue and Labels.

noinline: keeping one lambda as an object

An inline function inlines all its function parameters by default. Sometimes you need to treat one lambda as a real object, for example to store it in a variable or pass it to a non-inline function. Mark that parameter noinline:

Kotlin noinline parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is running now, registered: 1, running later. The parameter now is pasted in and costs nothing. The parameter later stays a real function object, so it can be stored in a list.

Without noinline, the compiler refuses to let an inlined lambda escape:

Kotlin Storing an inlined lambda (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The message is main.kt:4:18: error: illegal usage of inline parameter 'action: () -> Unit'. Add 'noinline' modifier to the parameter declaration. Because an inlined lambda has no object, there is nothing to store. The error even tells you the fix.

crossinline: no non-local return allowed

Sometimes an inline function calls its lambda not directly, but from inside another lambda or object, for instance from a Runnable. Then a non-local return in the caller's lambda would be dangerous: the code might run after the function it would return from has already finished. Kotlin forces you to promise that you will not do that, with crossinline:

Kotlin crossinline in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is created, not run yet, before, the body, after. The block is still pasted inline (inside the Runnable), so there is no lambda object, but a bare return inside the block is forbidden. Try to return from it and the compiler objects:

Kotlin return inside a crossinline lambda (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The message is main.kt:6:9: error: 'return' is prohibited here. Use return@runLater if you want to leave only the lambda.

Modifier Lambda is inlined Non-local return Can be stored or passed on
(default, in an inline function) yes allowed no
noinline no not allowed yes
crossinline yes not allowed used inside another lambda or object

reified type parameters

On the JVM, generic type arguments are erased at run time: inside fun <T> foo() the program does not know what T is, so x is T does not compile. Type Erasure and reified goes deeper, but the quick version is that an inline function can mark its type parameter reified, and then T is replaced by the real type at each call site:

Kotlin A reified type parameter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

You get two, 3.0, null, T is Int and T is List. The is T check works because the compiler pastes a real check like item is String at each call site. Note that even with reified, type arguments of generic types are still erased: T::class.simpleName prints List, not List<String>.

Without reified the same code does not compile:

Kotlin Checking a plain type parameter (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler says main.kt:3:21: error: cannot check for instance of erased type 'T (of fun <T> List<Any>.firstOfType)'. That is the cue to add inline and reified.

Inline properties and restrictions

Property accessors without a backing field can be inline too (inline val), which is how some Duration helpers work. A few rules to remember:

  • A public inline function cannot use non-public API from its module (private or internal functions), because its body is copied into other modules. The compiler reports this as an error.
  • Recursive functions cannot be inline, since inlining would never end.
  • Inline function parameters can only be called or passed on to other inline functions' inline parameters, unless marked noinline.
  • Big inline functions bloat the compiled code. Keep them small, or move the heavy part into a normal function and inline only the thin wrapper.

When to use and when to avoid

Use inline when you write a small function that takes a lambda and gets called often (custom measure, use-like helpers, withLock-style wrappers), or when you need reified. Skip it for functions without lambda parameters, for big bodies, for APIs you may later change (a public inline function's body is baked into callers, so changing it requires recompiling them), and for lambdas you want to keep around as objects.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the inline modifier do?

    inline tells the compiler to paste the function body (and the lambdas passed to it) into each call site, so no function object is created.
  2. 2. Why is a bare return allowed in a lambda passed to the inline forEach, but not in a lambda passed to an ordinary function?

    After inlining, the lambda body sits inside the enclosing function, so return can leave that function (a non-local return).
  3. 3. Which modifier lets an inline function store one of its lambda parameters in a list?

    noinline keeps the parameter as a real function object, so it can be stored or passed to non-inline code.
  4. 4. What is reified used for?

    An inline function can mark a type parameter reified, and the compiler substitutes the real type at each call site so is T and T::class work.
  5. 5. What does crossinline forbid?

    crossinline keeps the lambda inlined but bans non-local return, because the lambda may run later inside another lambda or object.

Summary

  • inline pastes a function and its lambda arguments into the call site: no lambda object, no call.
  • Inlining makes non-local return possible; use return@label to leave only the lambda.
  • noinline keeps one lambda parameter as a real object; crossinline keeps it inline but forbids non-local return.
  • reified type parameters need inline and give you is T and T::class at run time.
  • Use inline for small lambda-taking functions; avoid it for big bodies or functions without function parameters.

Next: Extension Functions