Constants in Scala

Constants

Scala supports constants of character, string, boolean, and numeric values.

object ConstantsExample {

  // Define a constant value.
  val s: String = "constant"

  def main(args: Array[String]): Unit = {
    println(s)

    // Constants can be used anywhere a variable can be used.
    val n: Int = 500000000

    // Constant expressions perform arithmetic with arbitrary precision.
    val d: Double = 3e20 / n
    println(d)

    // Numeric constants have no type until they are given one.
    println(d.toLong)

    // A number can be given a type by using it in a context that requires one, such as a variable assignment or function call.
    // For example, here math.sin expects a Double.
    println(math.sin(n))
  }

}

To run the program, save the code in a file named ConstantsExample.scala and use scalac to compile it, followed by scala to execute it.

$ scalac ConstantsExample.scala
$ scala ConstantsExample
constant
6.0E11
600000000000
-0.28470407323754404

Now that you understand how to use constants in Scala, let’s explore other features of the language.