TExcelTAD
Home › Scala › Scala Variables

Scala Variables

A variable gives a name to a value so you can use it later. Scala has two kinds: val, which can never be reassigned, and var, which can. Idiomatic Scala uses val almost everywhere and reaches for var only when there is a clear reason.

val: immutable bindings

scala · try it yourself
@main def run(): Unit =
  val city = "Lisbon"
  val population = 545_000
  val area = 100.05
  println(s"$city has $population people on $area km²")
Lisbon has 545000 people on 100.05 km²

Underscores in number literals (545_000) are only for readability; the value is 545000.

Trying to reassign a val is a compile-time error, not a runtime surprise:

scala
val city = "Lisbon"
city = "Porto"
text
-- [E052] Type Error: main.scala:2:7
2 |  city = "Porto"
  |  ^^^^^^^^^^^^^
  |  Reassignment to val city

var: mutable variables

A var can be given a new value of the same type as often as you like.

scala · try it yourself
@main def run(): Unit =
  var balance = 100
  println(s"Start: $balance")
  balance = balance - 30
  balance -= 20       // shorthand for balance = balance - 20
  balance += 5
  println(s"End: $balance")
Start: 100
End: 55

The type is fixed when the variable is created. balance = "zero" would not compile because balance is an Int.

val vs. var

val var
Can be reassigned no yes
Thread-safe to share yes (if the value itself is immutable) needs care
Typical use almost everything counters, loop state, performance-critical code

Note: val makes the name immutable, not necessarily the object. A val that holds a mutable ArrayBuffer can still have items added to it. Combine val with immutable collections for truly fixed data.

Type inference and explicit types

Scala infers the type from the value on the right. You can still write it yourself, which is useful for documentation or when you want a wider type than the one inferred.

scala · try it yourself
@main def run(): Unit =
  val count = 42            // Int
  val ratio = 0.75          // Double
  val big: Long = 42        // Int literal widened to Long
  val label: Any = "hello"  // any value fits in Any
  println(count.getClass.getSimpleName)
  println(ratio.getClass.getSimpleName)
  println(big.getClass.getSimpleName)
  println(label)
int
double
long
hello

getClass shows the underlying JVM type: Scala's Int, Double and Long compile to the fast primitive types int, double and long.

Declaring several values at once

You can unpack a tuple directly into several names:

scala · try it yourself
@main def run(): Unit =
  val (name, age) = ("Mira", 31)
  val (min, max) = (List(4, 9, 2).min, List(4, 9, 2).max)
  println(s"$name is $age")
  println(s"range: $min..$max")
Mira is 31
range: 2..9

lazy val

A lazy val is computed the first time it is used, not when it is declared. That is handy for expensive values that may never be needed.

scala · try it yourself
@main def run(): Unit =
  lazy val report =
    println("(building the report...)")
    "Report ready"
  println("Before first use")
  println(report)
  println(report)
Before first use
(building the report...)
Report ready
Report ready

The body ran exactly once, and only when report was first read.

Scope

A name is visible from where it is defined until the end of the enclosing block. An inner block may shadow an outer name by declaring a new one with the same name.

scala
val x = 1
locally:
  val x = 2   // a new x that hides the outer one
  println(x)  // 2
println(x)    // 1

Tip: If you are tempted to use var, first ask whether you can compute the final value in one expression — with if, match, or a collection method like sum or foldLeft.

Test yourself

What happens when you write val n = 1 and later n = 2?

  1. n becomes 2
  2. A runtime exception
  3. A compile error: reassignment to val
  4. A new variable is created

When is the body of a lazy val evaluated?

  1. When the program starts
  2. Every time it is read
  3. The first time it is read, then cached
  4. Never

Given var total = 10, which line does NOT compile?

  1. total += 5
  2. total = total * 2
  3. total = "ten"
  4. total -= 1