🔴 Scala Beginner

What is the difference between val and var in Scala?

Answer

In Scala, val declares an immutable binding — once assigned, the value cannot be reassigned. val x = 10; x = 20 // compile error. It is the preferred way to declare values in functional Scala, as it promotes immutability and thread safety. var declares a mutable variable that can be reassigned: var y = 10; y = 20 // ok. The Scala community strongly prefers val over var — using var is often a code smell. Note: val makes the binding immutable, not the object — a val list can still hold a mutable collection. For true immutability, use immutable collections with val.