In Scala, there are three types of variables: ‘val‘, ‘var‘, and ‘lazy val‘. These variables differ based on their immutability, initialization time, and reassignment capabilities.
1. ‘val‘ (Immutable variable)
A ‘val‘ is an immutable variable, meaning its value cannot be changed once it is initialized. In other words, they are like constants. As a best practice, you should prefer using ‘val‘ over ‘var‘ when possible to enforce immutability and avoid side effects in your code. ‘val‘ can be local, instance level, or at the object level.
Example:
val x = 10
Here, ‘x‘ has a constant value of 10, and you cannot change its value after the declaration.
2. ‘var‘ (Mutable variable)
A ‘var‘ is a mutable variable, meaning you can change its value after it has been initialized. Using mutable variables can lead to side effects and unpredictability in your code, so you should use them sparingly. Like ‘val‘, ‘var‘ can be local, instance level, or at the object level.
Example:
var y = 20
y = 30
In this case, the value of ‘y‘ can be changed after its initial assignment.
3. ‘lazy val‘ (Immutable lazy-initialized variable)
A ‘lazy val‘ is a combination of immutability and lazy initialization. Similar to ‘val‘, it is immutable, so its value cannot be changed after initialized. However, its value is not actually initialized until it is first used. This is useful when you have expensive or infrequently used computations, as it avoids unnecessary computations and memory usage. Once initialized, the value is stored and can be reused without re-evaluation.
Example:
lazy val z: Double = {
println("Computing z")
math.sqrt(50)
}
println("Before accessing z")
val result = z // This will print "Computing z" and then compute the square root of 50
println(s"z = $result") // This will print the value of z
In this example, the computation for ‘z‘ (calculating the square root of 50) is only executed when ‘z‘ is accessed for the first time. After that, the value is stored and can be reused without the computation happening again.
To sum up:
- ‘val‘: Immutable and initialized immediately
- ‘var‘: Mutable and initialized immediately
- ‘lazy val‘: Immutable and initialized upon first access