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
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 inlineval e_twice = e + e; // e_twice = 5.43656 this is evaluated at compile timeprintln("Value evaluated at compile-time:" + e_twice);}// inline function:inline def example( number:Int){ // the function call will be expanded at compile timeprintln("Number passed to function:" + number);}}
Free Resources