6

How do you declare compile time constants in Scala? In C# if you declare

const int myConst = 5 * 5;

myConst is in-lined as the literal 25. Is:

final val myConst = 5 * 5

equivalent or is there some other mechanism/ syntax?

Mario Galic
  • 47,285
  • 6
  • 56
  • 98
Rich Oliver
  • 6,001
  • 4
  • 34
  • 57

2 Answers2

10

Yes, final val is the proper syntax, with Daniel's caveats. However, in proper Scala style your constants should be camelCase with a capital first letter.

Beginning with a capital letter is important if you wish to use your constants in pattern matching. The first letter is how the Scala compiler distinguishes between constant patterns and variable patterns. See Section 15.2 of Programming in Scala.

If a val or singleton object does not begin with an uppercase letter, to use it as a match pattern you must enclose it in backticks(``)

x match {
  case Something => // tries to match against a value named Something
  case `other` =>   // tries to match against a value named other
  case other =>     // binds match value to a variable named other
}
Community
  • 1
  • 1
leedm777
  • 23,444
  • 10
  • 58
  • 87
6

final val is the way to do it. The compiler will then make that a compile-time constant if it can.

Read Daniel's comment below for details on what "if it can" means.

Rex Kerr
  • 166,841
  • 26
  • 322
  • 407
  • 15
    You forgot two important points: it must be statically resolved at compile time -- I'm not sure Scala does literal arithmetic at compile time -- and, very easy to get wrong, _it must not have a type_. If you declare it `final val myConst: Int = 5`, it will not be treated as a constant. – Daniel C. Sobral Jun 25 '12 at 19:09
  • 1
    Do you have a reference regarding _it must not have a type_? – ragazzojp May 31 '16 at 08:28
  • "The `final` modifier must be present and no type annotation may be given." https://scala-lang.org/files/archive/spec/2.12/04-basic-declarations-and-definitions.html#value-declarations-and-definitions – guymers Aug 09 '20 at 11:36