val vs var
In this page:
val vs var
val declares an immutable binding -- once assigned, it can never be reassigned -- while var declares a mutable variable that can be reassigned later. Scala idiom strongly favors val by default, only reaching for var when mutation is genuinely needed. This preference for immutability is a core part of Scala's functional programming style.
Warning: Attempting to reassign a val, like x = 5 after val x = 5, is a compile error, not a runtime one.
Example: val vs var
object Main extends App {
val x = 10
var y = 20
y = 30 // allowed, y is a var
println(s"x = $x, y = $y")
}
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: