Inline Functions

Sometimes, you might find a function declared using the inline keyword:

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 is inline? What “line” are we “in”?

Macro History

Many programming languages — C and C++ among them — support preprocessor macros:

#define max(X, Y)  ((X) > (Y) ? (X) : (Y))

Given the macro definition, you can use it like a regular function call:

foo = max(bar, goo);

As the name suggests, the “preprocessor” takes the raw source code and processes it before passing it to the actual compiler. In this case, the preprocessor expands the macro in place, replacing the above line with:

foo = ((bar) > (goo) ? (bar) : (goo));

As a result, we have syntax that looks like a function call, but we avoid some overhead involved with a function call versus just doing the work directly.

If we use the macro several times, though, there is a cost in terms of app size. We have the “expanded” macro code in several places, rather than it being just implemented in a single function body.


Prev Table of Contents Next

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