Inline Basics
Inline is a way to tell the compiler to paste code at the call site. The pasted code runs exactly like the plain code runs.
An inlined method doubles the input
The inline method doubles its input. The plain method doubles the same input.
inline def doubleIt(x: Int): Int = x * 2
def plainDouble(x: Int): Int = x * 2
@main def main(): Unit =
println(doubleIt(21))
println(plainDouble(21))An inline value doubles to 6
The inline value holds 3. Doubling it gives 6.
inline val MaxRetries = 3
@main def main(): Unit =
println(MaxRetries)
println(MaxRetries * 2)An inline method picks the larger number
The inline method compares two numbers. It returns the larger one in each call.
inline def larger(a: Int, b: Int): Int = if a > b then a else b
@main def main(): Unit =
println(larger(9, 4))
println(larger(2, 8))Example
inline val Price = 40
inline def half(x: Int): Int = x / 2
@main def main(): Unit =
println(Price)
println(half(Price))
println(Price - half(Price))Key points
- Inline def: An inline def is a method the compiler pastes at the call site.
- Call site: A call site is the place where a method is called.
- Inline val: An inline val is a constant value the compiler pastes where it is used.
- Small method: A tiny method is a good fit for inline because its pasted code stays short.
- Plain version: A plain method gives the same answer as its inline version.
In this example, the inline value holds the price 40. The inline method halves any number it receives. The main program prints the price, its half, and the price left after the half is taken away.
Note
Scala keeps a plain method as one shared block of code, so inline is a choice and not the default.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Scastie
Exercise
What does an inline def ask the compiler to do?