Open In App

Reassignment of val in Scala

Last Updated : 04 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Scala is a general-purpose, high-level, multi-paradigm programming language. It is a pure object-oriented programming language that also provides support to the functional programming approach. In Scala, there are two ways of declaring variables.

  1. Using var
  2. Using Val

Using var! as in Variable

It allows the reassignment of the reference variable to a different value but does not allow a change of the data type of the reference variable.

Example 1:

Scala




object Main {
  def main(args: Array[String]) {
    var x = 5
    Console println x
    x = 6 // allowed
    Console println x
    // x = "six" not allowed, type mismatch  
  }
}


Output:

 

It does not allow the programmer to change the value as well as the data type of the declared reference variable.

Using val as in Variable

Example 2:

Scala




object Main {
  def main(args: Array[String]) {
      val x = 5;
    Console println x
    // x = 6 not allowed
  }
}


Output:

 

Both var and val can be used with mutable and immutable data types.

As we know that everything in Scala is an object, we are allowed to call their member functions on them. It is totally independent of the keyword used to declare them.

Example 3:

Scala




import scala.collection.mutable
  
object Main {
  def main(args: Array[String]) {
    val map = mutable.Map[Int, String]()
    map += (1 -> "One")
    map += (2 -> "Two")
    Console println map
    // map = mutable.Map[Int, String]()
    // not allowed, reassignment to val
  }
}


Output:

 

Here we are allowed to add entries to the map as it is not changing the object stored in the reference variable map.

But using the assignment operator on a map is not allowed as it changes the object while maintaining the data type.

Exact behavior can be observed with Arrays. Since we cannot change the size of an Array after declaration the object value cannot be changed (more on this when we refer to memory management in Scala) but the value stored at different indexes can be updated.

Example 4:

Scala




object Main {
  def main(args: Array[String]) {
    val array = Array("one", "two")
    for (num <- array) {
        Console println num
    }
    array(1) = "three"
    for (num <- array) {
        Console println num
    }
  }
}


Output:

 

 

In short, as long as the object is not being changed we can update the value of a variable declared using val keyword.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads