Variables in Scala

Our first program will demonstrate variable declaration and initialization in Scala. Here’s the full source code:

object Variables {
  def main(args: Array[String]): Unit = {
    // var declares a mutable variable
    var a = "initial"
    println(a)

    // You can declare multiple variables at once
    var b, c = 1
    println(s"$b $c")

    // Scala will infer the type of initialized variables
    var d = true
    println(d)

    // Variables declared without initialization are not allowed in Scala
    // Instead, we can use Option to represent a potentially uninitialized value
    var e: Option[Int] = None
    println(e.getOrElse(0))

    // The val keyword is used to declare immutable variables (constants)
    val f = "apple"
    println(f)
  }
}

In Scala, variables are explicitly declared and used by the compiler to check type-correctness of function calls.

var declares a mutable variable. You can change its value later in the program.

You can declare multiple variables at once, but in Scala, they will all have the same value.

Scala will infer the type of initialized variables, so you don’t always need to specify the type explicitly.

Unlike some other languages, Scala doesn’t allow uninitialized variables. Instead, we can use Option to represent a potentially uninitialized value. Here, we use getOrElse(0) to print 0 if the value is not set.

The val keyword is used to declare immutable variables (constants). Once a value is assigned to a val, it cannot be changed.

To run the program, save it as Variables.scala and use the Scala compiler (scalac) to compile it, then run it with scala:

$ scalac Variables.scala
$ scala Variables
initial
1 1
true
0
apple

This example demonstrates basic variable declaration and usage in Scala. As you continue learning, you’ll discover more advanced features and idioms specific to Scala.