Naming convention for Scala constants?

What is the naming convention for Scala constants? A brief search on StackOverflow offers CamelCase uppercase (first line below), but I wanted to double check.

val ThisIsAConstant = 1.23 val THIS_IS_ANOTHER_CONSTANT = 1.55 val thisIsAThirdConstant = 1.94 

What style is recommended by Scala?

+75
scala naming-conventions constants
Mar 16 '12 at 22:50
source share
3 answers

The officially recommended style (and I mean officially) is the first style, the camel with the first letter is upper case. This is clearly described by Odersky in the Scala Program.

The style is also accompanied by a standard library and has some support in the semantics of the language: identifiers starting with upper case are considered as constants in comparison with the pattern.

(section 6.10, p. 107 in the second edition)

+105
Mar 17 2018-12-12T00:
source share

(This is a commentary on the addition to Daniel, but I am posting it as an answer in favor of syntax highlighting and formatting.)

Daniel believes that the style of using the initial capital letter, which is important in the semantics of the language, is more subtle and important than I initially gave him credit when I learned Scala.

Consider the following code:

 object Case { val lowerConst = "lower" val UpperConst = "UPPER" def main(args: Array[String]) { for (i <- Seq(lowerConst, UpperConst, "should mismatch.").map(Option.apply)) { print("Input '%s' results in: ".format(i)) i match { case Some(UpperConst) => println("UPPER!!!") case Some(lowerConst) => println("lower!") case _ => println("mismatch!") } } } } 

Naively, I would expect that he will reach all cases in the match. Instead, it prints:

 Input 'Some(lower)' results in: lower! Input 'Some(UPPER)' results in: UPPER!!! Input 'Some(should mismatch.)' results in: lower! 

What happens is that case Some(lowerConst) obscures val lowerConst and creates a local variable with the same name that will be populated anytime the Some string containing the string is evaluated.

True, there are ways around it, but the easiest way is to follow the style guide for permanent naming.

If you cannot follow the naming convention, then, as @reggoodwin points out in the comments below, you can put the variable name in ticks, for example

 case Some(`lowerConst`) => println("lower!") 
+38
Mar 17 '12 at 18:25
source share

The names of the constants must be in the upper camel case. That is, if a member is final, immutable and belongs to a package object or object , it can be considered a constant .... The method, values ​​and names of variables should be in the lower camel case

http://docs.scala-lang.org/style/naming-conventions.html#constants-values-variable-and-methods

+5
Oct 13 '13 at 12:30
source share



All Articles