val vs var
A val is a label stuck permanently on a value, like a name written in permanent marker, while a var is a label written in pencil that you can change. Most Scala coders prefer val for safety.
In this page:
Syntax
val name: Type = value // immutable
var name: Type = value // mutable
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Trying to reassign a
val, as inx = 20, which givesreassignment to val; usevarif it must change. - Using
vareverywhere, whenvalis safer and should be the default. - Assuming a
valholding a mutable object like anArrayBufferis frozen, when only the reference is fixed and the contents can still change.
🔒
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: