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
@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:
val city = "Lisbon"
city = "Porto"-- [E052] Type Error: main.scala:2:7
2 | city = "Porto"
| ^^^^^^^^^^^^^
| Reassignment to val cityvar: mutable variables
A var can be given a new value of the same type as often as you like.
@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:
valmakes the name immutable, not necessarily the object. Avalthat holds a mutableArrayBuffercan still have items added to it. Combinevalwith 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.
@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:
@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.
@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.
val x = 1
locally:
val x = 2 // a new x that hides the outer one
println(x) // 2
println(x) // 1Tip: If you are tempted to use
var, first ask whether you can compute the final value in one expression — withif,match, or a collection method likesumorfoldLeft.
Test yourself
What happens when you write val n = 1 and later n = 2?
nbecomes 2- A runtime exception
- A compile error: reassignment to val
- A new variable is created
When is the body of a lazy val evaluated?
- When the program starts
- Every time it is read
- The first time it is read, then cached
- Never
Given var total = 10, which line does NOT compile?
total += 5total = total * 2total = "ten"total -= 1