Search⌘ K

Immutable Variables

Explore how to declare immutable variables in Scala with the val keyword. Understand why immutable variables act like constants and cannot be reassigned, which promotes safer and more predictable code. This lesson prepares you to use Scala variables effectively by distinguishing immutability from mutability.

We'll cover the following...

Immutable is defined as unchangeable and is precisely what an immutable variable is; unchangeable.

Immutable variables are basically like constants; once they are assigned a value, that value can never change.

Declaring an Immutable Variable

To declare an immutable variable, we use the val keyword. Let’s create a variable named message that is assigned a String value.

Scala
val message: String = "Hello World"
println(message)

Oh no! You just realized you sent the wrong message. Let’s try to reassign a value to the variable message.

Scala
val message: String = "Hello World"
message = "Hello Educative"
println(message)

The above code would give you a runtime error error: reassignment to val letting you know that val cannot be reassigned a value.

In Scala, the general rule is to use the val field unless there’s a good reason not to.


Now, let’s move on to mutable variables that can be reassigned values.