← Back to Scala Course | Chapter 2: Variables & Types | Lesson 1 of 8

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:

  1. val vs var
Syntax
scala
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

markup
object Main extends App {
  val x = 10
  var y = 20

  y = 30 // allowed, y is a var
  println(s"x = $x, y = $y")
}
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
  1. Trying to reassign a val, as in x = 20, which gives reassignment to val; use var if it must change.
  2. Using var everywhere, when val is safer and should be the default.
  3. Assuming a val holding a mutable object like an ArrayBuffer is 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.