Scala Tutorial: var vs val

Scala Tutorial: var vs val

When it comes to variable assignment, newcomers to Scala are often confused by the difference between val and var. In this tutorial, we explain when to use val vs var and provide some basic examples of using each.

When to use val

When you assign a variable with val, you are saving the output of some computed value for later use. This makes val immutable meaning it cannot be changed after initial assignment.

Example:

val name = "Joe"
name = "Ted" //error: reassignment to val

In the example above, notice how we declare an immutable variable name using val. If we try and reassign the variable, we get an error.

As a general rule, use val when you want to assign an immutable value that won't change.

When to use var

When you assign a variable with var, you are creating a mutable variable. This means you can reassign the value after its initial assignment.

Example:

var name = "Joe"
name = "Ted" // reassigns the variable name to "Ted"

In the above example, we are able to reassign the variable name because of using var.

PLEASE NOTE

Although using val means immutability, it doesn't mean the value itself can't be modified. For example:

val array = Array(1,2,3)
array(0) = 4 // array now Array(4,2,3)
array = Array(5,6,7) //error: reassignment to val

In the example above, we are able to modify the existing array variable because we are changing the existing reference to Array. When we try to reassign array to a new instance of Array we get a reassignment error.

Conclusion

Use var when you want to declare a mutable variable that can be reassigned. Use val when you want to reference the output of an operation for later use. Remember that while val means immutability, it doesn't mean a mutable value assigned to val can't be changed.

Responses

Alexander Joseph
February 13, 2018
great explanation as well.
Alexander Joseph
February 13, 2018
true enough
StackChief LLC
February 10, 2018
great read.
agreed
- StackChief LLC

You might also like