Why val declaration doesn't follow scala constants naming convention?

Viewed 429

In Scala val is used for creating constants and the naming convention for Scala Constants is to use UpperCamelCase convention. (https://docs.scala-lang.org/style/naming-conventions.html#constants-values-variable-and-methods)

A generalization for this rule should be all vals should be in UpperCamelCase.

i.e. if a variable is declared using val keyword its name should be in UpperCamelCase. However I see examples on Scala's website exploiting this rule.

What am I missing here?

3 Answers

Put simply:

A constant only has one value while the program is running. It is either fixed at compile time, e.g. Pi, HoursInDay, or is an immutable value inside a top-level object.

A val is an immutable variable. It cannot be changed once it is set, but it may be set to different values each time the containing code is called.

Coding style suggests final constants to be uppercased:

if the member is final, immutable and it belongs to a package object or an object, it may be considered a constant

For example, note how scala.math.PI is defined as final:

@inline final val Pi = java.lang.Math.PI

vals inside objects are final in the sense they cannot be overridden so the following makes sense even though MyConstant it is not explicitly declared final:

object Container {
  val MyConstant = ...
}

If the val is not final, the style suggest lower case naming.

val in Scala is not only for defining Constants, it's also for defining Values. So, as Scala documentation states at https://docs.scala-lang.org/style/naming-conventions.html#constants-values-variable-and-methods :

For defining Constants you should use UpperCamelCase style where we tell these items Constant when:

If the member is final, immutable and it belongs to a package object or an object, it may be considered a constant.

For example:

object Container {
  val MyConstant = ...
}

While method, value and variable names should be in lowerCamelCase style like:

val myValue = ...
def myMethod = ...
var myVariable = ...
Related