All lessons

Variables

7 min · Scala

Store values in named boxes called variables.

Scala · Variables0/5 cleared

Enemy 1 of 5

Type inference

Once a program does more than print one fixed message, you need somewhere to keep values so you can use them more than once, pass them around, or update them as the program runs. A variable is just a name attached to a value — instead of typing the same string or number over and over, you give it a label and refer to that label instead.

This matters more than it sounds: naming a value also documents what it means. `val price = 5` tells the next reader (often you, a week later) what that `5` represents, in a way that a bare `5` sitting in the middle of an expression never could.

Scala gives you two ways to bind a name to a value: `val` and `var`. A `val` is immutable — once it's set, it can never be reassigned, and attempting to do so is a compile error. A `var` is mutable and can be reassigned later with `name = newValue`.

Scala's culture strongly favors `val` over `var`, which surprises people coming from languages where every variable is reassignable by default. The reasoning: a value that can't change is one less thing to track mentally while reading code, and it rules out a whole class of bugs where something gets mutated somewhere unexpected. Reach for `var` only when you genuinely need a value to change over time (like a running counter); default to `val` everywhere else.

Notice that `val name = "Ada"` doesn't mention a type anywhere. Scala is statically typed — every value has a fixed type known at compile time — but the compiler is smart enough to look at the right-hand side of `=` and figure out the type on its own. Here it sees a string literal and infers `name: String`, so you don't have to spell it out.

You can still write the type explicitly (`val name: String = "Ada"`), and sometimes you'll want to, especially when the inferred type would be less specific than you intend. But for straightforward cases, letting Scala infer the type keeps the code shorter without giving up any safety — the type is still checked, it's just not typed out by hand.

You
Cold-Start Frostling

Loading editor...

Ln 1, Col 1Spaces: 4
Sign up to fightTarget output: Ada