Inline Functions: Like Macros

An inline function in Kotlin works like a preprocessor macro. The compiler takes all occurrences of calls to that inline function and replaces them with the actual function body, much like how the C preprocessor replaces all occurrences of the macro with the macro definition.

What We Write

All we do is add inline to the function declaration:

inline fun max(x: Int, y: Int): Int = if (x > y) x else y

fun main() {
  val bigger = max(3, 7)

  println("The larger of 3 and 7 is $bigger")
}

What the Compiler Compiles

The compiler does not generate an actual function, despite our declaration. Rather, each place that we call the function, Kotlin will compile the code from the function body. It will be as if we wrote:

fun main() {
  val bigger = if (3 > 7) 3 else 7

  println("The larger of 3 and 7 is $bigger")
}

We gain some performance by avoiding an actual function call. But, if we call max() in many places, we wind up with many copies of the max() code in the compiled app, and our app will be bigger.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.