Reference versus value immutability

According to the section earlier, val is used to declare immutable variables, so can we change the values of these variables? Will it be similar to the final keyword in Java? To help us understand more about this, we will use the following code snippet:

scala> var testVar = 10
testVar: Int = 10

scala> testVar = testVar + 10
testVar: Int = 20

scala> val testVal = 6
testVal: Int = 6

scala> testVal = testVal + 10
<console>:12: error: reassignment to val
testVal = testVal + 10
^
scala>

If you run the preceding code, an error at compilation time will be noticed, which will tell you that you are trying to reassign to a val variable. In general, mutable variables bring a performance advantage. The reason is that this is closer to how the computer behaves and because introducing immutable values forces the computer to create a whole new instance of an object whenever a change (no matter how small) to a particular instance is required

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.121.86