🎓 A1Learner
🔍
0 of 45 lessons completed

Compile-Time Operations

Compile-time operations are operations that run during compilation. They compute values before the program runs.

ConstValue reads 5 from its type

The type 5 stands for the number 5. Doubling that number gives 10.

import scala.compiletime.constValue
@main def main(): Unit =
  println(constValue[5])
  println(constValue[5] * 2)

ConstValue reads a word from its type

The type hi stands for the word hi. That word has length 2.

import scala.compiletime.constValue
@main def main(): Unit =
  println(constValue["hi"])
  println(constValue["hi"].length)

SummonInline finds a given number

The given value for Int is 8. Adding 2 to it gives 10.

import scala.compiletime.summonInline
given Int = 8
@main def main(): Unit =
  println(summonInline[Int])
  println(summonInline[Int] + 2)

Example

import scala.compiletime.{constValue, summonInline}
given Int = 8
@main def main(): Unit =
  println(constValue[5])
  println(summonInline[Int])
  println(constValue[5] + summonInline[Int])

Key points

  • Compile time: Compile time is the period when the compiler turns source code into a program.
  • ConstValue: ConstValue reads a literal type and returns its value.
  • Given: A given is a value the compiler can find for a type when it is needed.
  • SummonInline: SummonInline finds a given value at compile time.
  • Use constValue to turn a type such as 5 into the number 5.

In this example, the given value for Int is 8. The main program prints the compile-time value 5 and the given value 8. It then prints the sum of those two values.

Note

Scala compile-time operations run in the compiler, so they cannot read run-time input.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Scastie

Exercise

When does a compile-time operation run?