108

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

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

Which is recommended Scala style?

Michal Kordas
  • 10,475
  • 7
  • 58
  • 103
grautur
  • 29,955
  • 34
  • 93
  • 128
  • 2
    When it's to be used like a conventional, utterly-predefined C-/Java-style constant, the first one. The second form—and underscores in names in general—is never really used. The third is generally used for immutable values that are generated dynamically. – Destin Mar 16 '12 at 23:11
  • 3
    I'm using the second one, but mostly to prior java experience. Disregard that, I think most official way is the first one (since it is used in scala lib itself, e.g. look at π which is defined as `Pi`). – om-nom-nom Mar 16 '12 at 23:16

3 Answers3

140

The officially recommended style (and I do mean officially) is the first style, camel case with first letter are upper case. It's laid down clearly by Odersky on Programming in Scala.

The style is also followed by the standard library, and has some support in language semantics: identifiers starting with upper case are treated as constants in pattern matching.

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

wjohnson
  • 711
  • 1
  • 8
  • 19
Daniel C. Sobral
  • 295,120
  • 86
  • 501
  • 681
  • 1
    Looking at the official Scala naming guidelines, variant 3 is in fact the recommended style: http://docs.scala-lang.org/style/naming-conventions.html#values_variable_and_methods – mxk Aug 09 '13 at 08:28
  • 5
    @Matthias That doesn't cover constants. A terrible oversight, but, trust me, not only that is not correct, but the third style _will cause problems_, as soon as you use it on a pattern match. – Daniel C. Sobral Aug 09 '13 at 18:07
  • 1
    @Matthias I've now opened [an issue](https://github.com/scala/scala.github.com/issues/231) about it. I'd normally do the fix and PR it, but I'm sadly lacking time these days. :( – Daniel C. Sobral Aug 09 '13 at 18:16
  • It must be a constant to be first letter upper case, which means val, immutable and in a package object or an object – samthebest Oct 09 '13 at 16:15
  • @samthebest Is that a question or a remark? I'm not sure I understand what you are saying. – Daniel C. Sobral Oct 09 '13 at 18:28
  • Clarifying the definition of a constant - in particular "val ThisIsAConstant = 1.23" is WRONG if it is not in a package object or object. – samthebest Oct 11 '13 at 15:30
  • 1
    @samthebest Non-sense. It makes perfect sense in traits, and even at the scope of functions it makes sense if you are going to use it on pattern matching. – Daniel C. Sobral Oct 11 '13 at 23:28
  • @DanielC.Sobral I understand that it can be useful for pattern matching, but if you do not follow the official style guide then you are violating the definition of constant. One cannot consider a immutable val in a trait a constant (unless it is final, in which case it does make sense), because multiple distinct instances could exist if a class extended such a trait. Furthermore multiple distinct instances could exist if allowed in function scope. A constant, by definition, must be absolutely constant in a package namespace - it can only be one thing; constant. – samthebest Oct 13 '13 at 12:45
  • @samthebest Constant != unique. Who cares if there are multiple instances of a constant? And even if we did go for uniqueness, Scala goes for _path dependent types_, where uniqueness is not tied to a global scope but is determined _per instance_. But let's go for the true test: declare, in a trait, something like `final val x = 5`. Make an `object` extend that trait, and then refer to `x` in that object from another class. Compile that class with `-optimise`, use `javap` and see that `x` was replaced by constant 5. – Daniel C. Sobral Oct 14 '13 at 04:58
  • @DanielC.Sobral As I said, I agreed a final constant makes sense in a trait. "Who cares if there are multiple instances of a constant?" because a constant must be constant up to package namespace - that's simply the definition. It means that when reading any code in the package, one knows straight away what the value of the constant is without having to deduce how the constant was initialised. If you are so convinced that it's acceptable style in a function or class, find a single example in the Scala source :) – samthebest Oct 14 '13 at 09:14
  • @samthebest See [`Scanner`](http://www.scala-lang.org/api/current/index.html#scala.xml.dtd.Scanner). – Daniel C. Sobral Oct 15 '13 at 17:41
  • @DanielC.Sobral Their not upper *camel* case ;), try again :). to be honest I have no idea when to use all caps, the style guide has no mention. – samthebest Oct 16 '13 at 16:26
  • @samthebest There's no all caps in Scala. The Scala style for constants is camel case with first letter uppercase. – Daniel C. Sobral Oct 16 '13 at 19:05
  • 1
    I've been using scalastyle to check for style violations in my code. But it doesn't seem to catch these naming convention errors for constants. Is there a way to enable a check that ensures constants are named in camel case with the first letter capitalized? – jithinpt Nov 22 '16 at 20:09
47

(This is an addendum comment to Daniel's answer, but I'm posting it as an answer for the benefit of syntax highlighting and formatting.)

Daniel's point about the style of using an initial capital letter being important in the language semantics is more subtle and important than I originally gave it credit for 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 have expected that to reach all of the 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's going on is that the case Some(lowerConst) shadows the val lowerConst and creates a local variable of the same name which will be populated any time a Some containing a string is evaluated.

There are admittedly ways to work around it, but the simplest is to follow the style guide for constant naming.

If you can't follow the naming convention, then as @reggoodwin points out in the comments below, you can put the variable name in ticks, like so

case Some(`lowerConst`) => println("lower!")
Leif Wickland
  • 3,693
  • 26
  • 43
  • 1
    Adding to Leif's answer: this scenario is mentioned in Programming in Scala 15.2. If there is no choice but to use a constant starting with a lower case then it can be escaped with back ticks, e.g. case \`pi\` => .... – reggoodwin May 26 '13 at 17:42
  • 3
    if case Some(lowerConst) shadows the val lowerConst, why isn't case Some(UpperConst) shadowing the val UpperConst ? – Adrian Apr 11 '16 at 18:44
  • @Leif Wickland @Daniel C. Sobral Do value of constants matters for sake of convention of pattern matching? e.g. `val UpperConst = "UPPER_CONST"` okay or it should be `val UpperConst = "UpperConst"` – nir Aug 15 '16 at 22:47
9

Constant names should be in upper camel case. That is, if the member is final, immutable and it belongs to a package object or an object, it may be considered a constant .... Method, Value and variable names should be in lower camel case

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

user1338062
  • 11,939
  • 3
  • 73
  • 67
samthebest
  • 30,803
  • 25
  • 102
  • 142
  • Do value of constants matters for sake of convention of pattern matching? e.g. val `UpperConst = "UPPER_CONST"` like part java-style okay or it should be `val UpperConst = "UpperConst"` – nir Aug 15 '16 at 22:49