🎓 A1Learner
🔍
0 of 45 lessons completed

Inline Match

Inline match is a match the compiler chooses at compile time from a constant value. The compiler picks one branch before the program runs.

Inline match picks 10 for the type 1

The type 1 matches the second branch. That branch returns 10.

import scala.compiletime.constValue
inline def sizeOf[T]: Int = inline constValue[T] match
  case 0 => 0
  case 1 => 10
  case 2 => 20
  case _ => 99
@main def main(): Unit =
  println(sizeOf[1])

Inline match picks 20 for the type 2

The type 2 matches the third branch. That branch returns 20.

import scala.compiletime.constValue
inline def sizeOf[T]: Int = inline constValue[T] match
  case 0 => 0
  case 1 => 10
  case 2 => 20
  case _ => 99
@main def main(): Unit =
  println(sizeOf[2])

Inline match picks high for level 2

The inline value holds 2. The match picks the branch for 2.

inline val level = 2
inline def label: String = inline level match
  case 1 => "low"
  case 2 => "high"
  case _ => "unknown"
@main def main(): Unit =
  println(label)
  println(label.length)

Example

import scala.compiletime.constValue
inline def sizeOf[T]: Int = inline constValue[T] match
  case 0 => 0
  case 1 => 10
  case 2 => 20
  case _ => 99
@main def main(): Unit =
  println(sizeOf[1])
  println(sizeOf[2])
  println(sizeOf[1] + sizeOf[2])

Key points

  • Literal type: A literal type is a type that stands for one exact value, such as 1.
  • ConstValue: ConstValue is a compile-time operation that reads a literal type as a value.
  • Inline match: An inline match is a match the compiler resolves before the program runs.
  • Branch: A branch is one path inside a match.
  • Use inline match to pick a result from a known type at compile time.

In this example, the method matches a literal type to a number. The main program prints the result for 1 and the result for 2. It then prints the sum of those two results.

Note

Scala needs the match to be marked inline for the compiler to choose the branch early.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Scastie

Exercise

What does an inline constValue match choose from?