How to Reassignment to a Val in Scala

Suraj P Feb 02, 2024
  1. Reassignment to a val in Scala
  2. Conclusion
How to Reassignment to a Val in Scala

This article will teach about reassignment to a val in Scala.

Reassignment to a val in Scala

In Scala, reassignment to val is not allowed, but we can create a new val and assign the value to it.

Example code 1:

object MyClass {

    def main(args: Array[String])
    {
         val x = 10;
         x = x+10

         println(x)
    }
}

Output:

error: reassignment to val

We can see an error when reassigning the values to a val.

As a workaround, we can assign the result to a new val and use it.

Example code 2:

object MyClass {

    def main(args: Array[String])
    {
         val x = 10;
         val y = x+10

         println(y)
    }
}

Output:

20

Scala provides us with three ways to define things.

  1. val is used to define a fixed value, which cannot be modified.

    Example code: Here, the val x cannot be modified.

    object MyClass {
    
    	def main(args: Array[String])
    	{
    		 val x = 10;
    
    	}
    }
    
  2. var is used to define a variable, a value that can be modified.

    object MyClass {
    
    	def main(args: Array[String])
    	{
    		 var x = 10;
    		 x = x+10;
    		 println(x)
    
    		 x = x*1000
    		 println(x)
    
    	}
    }
    

    Output:

    20
    20000
    
  3. def is used to define a method

    Example code:

    object MyClass {
    
      def student = 2*3*4*5*6
    
    	def main(args: Array[String])
    	{
    		 println(student)
    	}
    }
    

    Output:

    720
    

Conclusion

In this article, we learned that we could not reassign values to a val as it declares the variable as the fixed value, so if we want to use a variable that keeps changing constantly, we can use var.

Author: Suraj P
Suraj P avatar Suraj P avatar

A technophile and a Big Data developer by passion. Loves developing advance C++ and Java applications in free time works as SME at Chegg where I help students with there doubts and assignments in the field of Computer Science.

LinkedIn GitHub