Ad space (banner)
Lesson 3 / 20

Variables (val and var)

This lesson covers declaring variables in Scala and the difference between immutable (val) and mutable (var).

A variable declared with val cannot be changed once its value is set. Use var when you do need to change it later. Scala style recommends reaching for val wherever possible.

The sample code declares an immutable val name = "Alice" and a mutable var age = 14, then changes only age.

A common early stumble is trying to change a val later and hitting a compile error. This immutable-by-default thinking is central to functional programming, and it heads off bugs where a value is overwritten unintentionally.

In professional work, the habit of using var only where a variable genuinely has to change leads to code with fewer bugs.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Scala directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)