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

val vs var

In this page:

  1. val vs var

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")
}
🔒

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.