Scala Variables

A variable is a convenient placeholder used to reference a computer memory address. Once a variable is created, it occupies a certain amount of memory space.

Based on the variable's data type, the operating system allocates memory and decides what will be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals, or letters in these variables.

Variable Declaration

Before learning how to declare variables and constants, let's first understand variables and constants.

  • Variable:A quantity whose value may change during program execution is called a variable. For example: time, age.
  • Constant:A quantity whose value does not change during program execution is called a constant. For example: the number 3, the character 'A'.

In Scala, use the keyword"var"to declare variables, and use the keyword"val"to declare constants.

Immutable Variable (val):

  • Using thevalkeyword declares an immutable variable, meaning once assigned, its value cannot be changed.
  • Similar to Java'sfinalvariable.

Mutable Variable (var):

  • Using thevarkeyword declares a mutable variable, whose value can be changed multiple times during the program's lifetime.
  • Similar to ordinary variables in Java.

An example of declaring a variable is as follows:

var myVar : String = "Foo"
var myVar : String = "Too"

The above defines the variable myVar, which we can modify.

An example of declaring a constant is as follows:

val myVal : String = "Foo"

The above defines the constant myVal, which cannot be modified. If the program attempts to modify the value of the constant myVal, it will cause a compilation error.


Variable Type Declaration

The variable's type is declared after the variable name and before the equals sign. The syntax for defining a variable's type is as follows:

var VariableName : DataType [=  Initial Value]

或

val VariableName : DataType [=  Initial Value]

Example

object VariableExample {
  def main(args: Array[String]): Unit = {
    // Declare an immutable variable
    val immutableVariable: Int = 10
    println(s"Immutable Variable: $immutableVariable")

    // Declare a mutable variable
    var mutableVariable: Int = 20
    println(s"Mutable Variable: $mutableVariable")

    // Modify the value of the mutable variable
    mutableVariable = 30
    println(s"Updated Mutable Variable: $mutableVariable")

    // Immutable variables cannot be reassigned; this will cause a compilation error
    // immutableVariable = 15 // Uncommenting this line will cause a compilation error
  }
}

The output of the above code is:

Immutable Variable: 10
Mutable Variable: 20
Updated Mutable Variable: 30

Variable Naming Conventions

Legal Characters:

  • Variable names must begin with a letter (A-Z or a-z) or an underscore (_).
  • Subsequent characters can be letters, digits (0-9), or underscores.
  • Variable names cannot be Scala keywords.

Camel Case Naming:

  • Variable names typically use camel case, where the first word starts with a lowercase letter and the first letter of subsequent words is capitalized.
  • For example:myVariableName, userAge, accountBalance。

Avoid Using Single-Character Variable Names:

  • Except for common counter variables (such asi, j, k), you should avoid using single-character variable names as much as possible to improve code readability.

Meaningful Variable Names:

  • Variable names should clearly express their purpose or meaning, avoiding vague or meaningless names.
  • For example:val age: Int = 25is better thanval a: Int = 25。

Scala-Specific Naming Conventions:

  • Try to avoid variable names that start with an underscore, as these are usually used to identify internal or private variables.
  • Combinations of letters and symbols can be used to name functions and methods, but this is rarely seen in variable naming.
  • Avoid using operator-like symbol combinations (such as++,--) as variable names, as this makes the code difficult to read and understand.

Variable Type Reference

In Scala, it is not necessary to specify the data type when declaring variables and constants. When the data type is not specified, it is inferred from the initial value of the variable or constant.

Therefore, if you declare a variable or constant without specifying its data type, you must provide its initial value; otherwise, an error will occur.

  • Explicit Type Declaration: Explicitly specify the variable's type.
  • Type Inference: Omit the type declaration and let the compiler infer the type.

Scala's type inference mechanism can automatically determine a variable's type, so we can omit the type declaration:

val inferredInt = 42  // 编译器推断为 Int
val inferredDouble = 3.14  // 编译器推断为 Double
val inferredString = "Hello, Scala!"  // 编译器推断为 String
val inferredBoolean = true  // 编译器推断为 Boolean

Type inference makes code more concise, but in complex scenarios, explicit type declarations can avoid confusion.

For explicit type declaration, follow the variable name with a colon and the data type:

val explicitInt: Int = 42
val explicitDouble: Double = 3.14
val explicitString: String = "Hello, Scala!"
val explicitBoolean: Boolean = true

Explicit declaration helps improve code readability and maintainability, especially when types are not easy to infer or are easy to confuse.

Example

object VariableTypesExample {
  def main(args: Array[String]): Unit = {
    // Explicit type declaration
    val explicitInt: Int = 42
    val explicitDouble: Double = 3.14
    val explicitString: String = "Hello, Scala!"
    val explicitBoolean: Boolean = true

    // Type inference
    val inferredInt = 42  // Compiler infers Int
    val inferredDouble = 3.14  // Compiler infers Double
    val inferredString = "Hello, Scala!"  // Compiler infers String
    val inferredBoolean = true  // Compiler infers Boolean

    // Mutable variable
    var mutableInt: Int = 10
    println(s"Initial mutableInt: $mutableInt")
    mutableInt = 20  // Modify variable value
    println(s"Updated mutableInt: $mutableInt")

    // Output all variables
    println(s"Explicit Int: $explicitInt")
    println(s"Explicit Double: $explicitDouble")
    println(s"Explicit String: $explicitString")
    println(s"Explicit Boolean: $explicitBoolean")

    println(s"Inferred Int: $inferredInt")
    println(s"Inferred Double: $inferredDouble")
    println(s"Inferred String: $inferredString")
    println(s"Inferred Boolean: $inferredBoolean")
  }
}

The output of the above code is:

Initial mutableInt: 10
Updated mutableInt: 20
Explicit Int: 42
Explicit Double: 3.14
Explicit String: Hello, Scala!
Explicit Boolean: true
Inferred Int: 42
Inferred Double: 3.14
Inferred String: Hello, Scala!
Inferred Boolean: true

Declaring Multiple Variables in Scala

In Scala, you can declare multiple variables at the same time. This not only makes the code more concise but also ensures the correlation of multiple variables declared on the same line.

In Scala, you can declare multiple variables simultaneously using methods such as comma separation, tuple destructuring, and for comprehensions.

You can declare multiple variables on one line separated by commas:

val xmax, ymax = 100  // xmax, ymax都声明为100

Example

object MultipleVariables {
  def main(args: Array[String]): Unit = {
    // Declare multiple immutable variables at the same time
    val a, b, c: Int = 5
    println(s"a: $a, b: $b, c: $c")

    // Declare multiple mutable variables at the same time
    var x, y, z: Int = 10
    println(s"x: $x, y: $y, z: $z")

    // Modify the value of the mutable variables
    x = 20
    y = 30
    z = 40
    println(s"Updated x: $x, y: $y, z: $z")
  }
}

If a method's return value is a tuple, we can use val to declare a tuple:

scala> val pa = (40,"Foo")
pa: (Int, String) = (40,Foo)

Example

object TupleDestructuring {
  def main(args: Array[String]): Unit = {
    // Use tuple destructuring to declare multiple variables at the same time
    val (a, b, c) = (1, 2, "hello")
    println(s"a: $a, b: $b, c: $c")

    // Use tuple destructuring to declare multiple mutable variables at the same time
    var (x, y, z) = (10, 20, "world")
    println(s"x: $x, y: $y, z: $z")

    // Modify the value of the mutable variables
    x = 30
    y = 40
    z = "Scala"
    println(s"Updated x: $x, y: $y, z: $z")
  }
}

Declaring Multiple Variables Using for Comprehensions

In a for comprehension, multiple variables can be declared simultaneously for iteration and generating new collections.

Example

object ForComprehension {
  def main(args: Array[String]): Unit = {
    // Declare multiple variables at the same time for iteration
    val numbers = List((1, "one"), (2, "two"), (3, "three"))
    for ((number, word) <- numbers) {
      println(s"Number: $number, Word: $word")
    }

    // Use a for comprehension to generate a new collection
    val newNumbers = for {
      (number, word) <- numbers
    } yield (number * 2, word.toUpperCase)

    println(s"New Numbers: $newNumbers")
  }
}
Other Extensions