val / var
Try it yourself →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
val brand = "Scala" var score = 10 score = 20 println(brand) println(score)
Expected output
Scala 20
When to use?
val is mostly preferred in functional style.
Common mistakes
- ⚠️ Reassigning a val causes a compilation error.