What are mutable and immutable variables in Scala?

In this shot, we’ll learn about the concept of mutable and immutable variables in Scala.

Variables are storage locations that hold values of different data types, such as integers, strings, or booleans. Variables in Scala are of two types:

  • Mutable
  • Immutable

Mutable means something is changeable after its creation; whereas, immutable means the oppositewe cannot change an immutable instance.

Mutable vs. Immutable

Scala has particular keywords, var and val, to distinguish between mutable and immutable variables.

Mutable vs. immutable variables

The var keyword

We can define mutable variables with the var keyword.

Syntax

To define a mutable variable without declaring its data type, we write the following code statement:

var mutable_var = "Hello World"
var mutable_var = 70

If we want to specify the data type of mutable variables, we follow the syntax below:

var mutable_var: String = "This is a mutable variable"
var mutable_var: Int = 70

The val keyword

We can define immutable variables with the val keyword.

Syntax

To define an immutable variable without declaring its data type, we write the following code statement:

val immutable_var = "This is an immutable variable"
val immutable_var = 70

If we want to specify the data type of immutable variables, we follow the syntax below:

val immutable_var: String = "Hello World"
val immutable_var: Int = 70
Copyright ©2024 Educative, Inc. All rights reserved