val / var
Constant (val) and variable (var).
Syntax
val constant = value // var variable = value
Description
val is assigned once (immutable), var can be changed later. The type is inferred from the value; you can specify it with : if you want.
Example
Loading editor…
This language is for reference/learning only — copy the code and try it in your own environment.
Expected output
Scala 20
When to use?
val is mostly preferred in functional style.
Common mistakes
- ⚠️ Reassigning a val causes a compilation error.