How to use val as in Variable In Other
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.
Reassignment of val in Scala
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.
- Using var
- Using Val