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 = "Kotlin" var score = 10 score = 20 println(brand) println(score)
Expected output
Kotlin 20
When to use?
Use val for values that won't change (safe).
Common mistakes
- ⚠️ Reassigning a val causes a compilation error.