Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: Compile time constants

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?

like image 853
Rich Oliver Avatar asked Jun 25 '12 18:06

Rich Oliver


People also ask

What are compile time constants?

A compile-time constant is a value that is computed at the compilation-time. Whereas, A runtime constant is a value that is computed only at the time when the program is running. 2. A compile-time constant will have the same value each time when the source code is run.

What is compile time initialization in Java?

4.1. Compile-Time Constants. A Java variable is a compile-time constant if it's of a primitive type or String, declared final, initialized within its declaration, and with a constant expression. Strings are a special case on top of the primitive types because they are immutable and live in a String pool.

What is a compile time constant in Java What is the risk of using it?

public static final variables are also known as a compile-time constant, the public is optional there. They are replaced with actual values at compile time because compiler know their value up-front and also knows that it cannot be changed during run-time.


2 Answers

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
}
like image 140
leedm777 Avatar answered Sep 30 '22 13:09

leedm777


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.

like image 24
Rex Kerr Avatar answered Sep 30 '22 11:09

Rex Kerr