What is inline in Scala 3?

Scala 3 offers a compile-time metaprogramming technique called inlining. Inlining means that the specified code is evaluated or expanded only at compile-time. This is useful for performance optimizations and provides a way to program with macros.

inline is a soft keywordkeywords that are context-sensitive. Using the keyword ensures that the inlining actually happens instead of just an attempt to inline. Using inlining also introduces operations that are guaranteed to run at compile time.

Inlining constants

This is the most simple form of inlining.

inline val e = 2.71828

Using the keyword inline ensures that all references to e are inlined (i.e., evaluated at compile time).

For example, if we use e in an expression, that expression is computed at compile-time. This optimization is called “constant folding.”

val e_twice = e + e // e_twice = 5.43656

The value of e_twice in this expression is computed at compile-time.

Inlining methods

Just like constants, methods can also be inlined. Using the modifier inline before the declaration specifies that this method is an inline method.

inline def example(number: Int) {
  println("Number passed to function:" + number)
}

When the function example is called from the main function, it is expanded only at compilation time. At compile-time, the call to the inlined method is replaced by the method.

example(3.14)

This function call in the main function is replaced by the function at compile time:

inline def example(number: Int) {
  println("Number passed to function: $number")
}

Code

The following code demonstrates the usage of inline.

object Example {
def main(args: Array[String]) {
inline val e = 2.71828; // variable declared inline
val e_twice = e + e; // e_twice = 5.43656 this is evaluated at compile time
println("Value evaluated at compile-time:" + e_twice);
}
// inline function:
inline def example( number:Int){ // the function call will be expanded at compile time
println("Number passed to function:" + number);
}
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved