Is an expression like 3600 * 24 evaluated at compile-time?

Viewed 86

In Scala, suppose I write

val oneDay = 3600L * 24 // seconds in one day
val twoDay = oneDay * 2 // seconds in two days

Is the final value of oneDay (i.e., 86400) computed at runtime or compile-time?

What about the final value of twoDay?

2 Answers

To be sure of the final values, I try to compile your code using:

scalac main.scala -Xprint:all

And, in the last phase, your code turn to be:

final <synthetic> def delayedEndpoint$Main$1: Unit = {
      Main.this.oneDay = 86400L;
      Main.this.twoDay = Main.this.oneDay().*(2);
      ()
    };

So, the first value is computed at compile-time but the second value will be computed at runtime.

With Scala 3.0 it is possible to use inline (or final as stated by @ghik) to make also the second value computed at compile time.

Yes, 3600L * 24 will be constant-folded and computed in compile time.

As for oneDay * 2, it depends on how oneDay is declared. If it's something like this:

object Constants {
  // note the `final` keyword and *no* explicit type
  final val oneDay = 3600L * 24

  val twoDay = oneDay * 2
}

then references to oneDay will also be seen as constants by the compiler and constant-folded.

Related