val and var
The logbook holds two kinds of facts. The club's name stays the same all season, but the week's total distance grows after every run. Scala asks you to say which is which, and that small choice prevents a whole family of bugs.
The rule
val binds once; var can be reassigned. Reach for val first.
val clubName = "Riverside Run Club"
var weekKm = 0.0
weekKm += 5.0 // fine: weekKm is now 5.0
weekKm = weekKm + 8.5 // fine: now 13.5
clubName = "Hillside Club" // compile error: Reassignment to val clubNamevalnames a value exactly once. From then on, the name always refers to that same value.varcan be given a new value later, but only of the same type.weekKm = "far"fails, becauseweekKmis aDouble.
You may write the type after a colon, or let Scala infer it:
val laps: Int = 12 // type written out
val moreLaps = 14 // type inferred: also IntInside a function, a val must get its value on the line that declares it. A bare val laps: Int there is a compile error, so there is never an "empty" value waiting to be filled in.
For values fixed for the whole program, Scala style uses UpperCamelCase names, usually at the top level of a file or inside an object:
val TrackLengthMeters = 400One subtlety: val freezes the name, not necessarily the thing it points to. A val holding a mutable collection can still have its contents changed. You will meet that case in the Data Structures section.
The shortcut
Write val every time. When the compiler says "Reassignment to val", stop and ask: does this value really change as the program runs? If yes, make it a var. If no, the compiler has just caught a bug for you.
The club's name
Never changes:
val clubName = "Riverside Run Club".
The trap: using var "just in case". Every var is a place where a value might change behind your back, so each one should earn its place.
Drills
Answer fast — trust the rule.
Which line fails to compile?
Given var weekKm = 0.0, which assignment is rejected?
Inside a function, what happens with val laps: Int and no value?
Which name follows Scala style for a program-wide constant?
When does the shortcut tell you to switch a val to a var?
Remember
valbinds once;varcan be reassigned with a value of the same type.- Write
valfirst, and switch tovaronly when the value really changes. - Trap:
var"just in case" — andvalfreezes the name, not a mutable object's contents.
