Reputation: 17
I am new to Scala and trying to understand the concept of immutability as it relates to Arrays and ArrayBuffers - however, I am getting tripped up with this concept.
I understand var
to represent a mutable object and val
to represent an immutable one.
var i = 10
i = 12
//OR
val i = 10
i = 12 //error - reassignment to val
So I have an example involving arrays and ArrayBuffers and maybe if someone can explain what exactly happens in memory and why these operations are allowed to happen. Like I said, I am still new to Scala and I was just unsure as to why these concepts were:
def main(args: Array[String]) :Unit =
{
val testArr:Array[Int] = new Array[Int](3)
testArr(0) = 1
testArr(1) = 2
testArr(2) = 3
val testArr2:Array[Int] = new Array[Int](3)
//testArr2 = Array(1,2,3) - reassignment to val
val arrBuffer = new ArrayBuffer[Int]
arrBuffer += 1
arrBuffer += 2
arrBuffer += 3
//arrBuffer = ArrayBuffer[Int](4,5,6) - reassignment to val
val addBuffer = ArrayBuffer[Int](4,5,6)
arrBuffer ++= addBuffer
}
Upvotes: 0
Views: 68
Reputation: 48420
The memory model differentiates between pointer-to-data (memory address) and the pointed-to-data (data itself). Consider
val x = Array(1,2,3)
The key is to understand that x
does not physically hold the data 1,2,3
, instead it holds just the reference (pointer) to the actual data, that is, it holds the memory location of where the data begins.
Contrast the following situations
val xa = List(1,2,3) // constant pointer to constant data
var xb = List(1,2,3) // non-constant pointer to constant data
val ya = Array(1,2,3) // constant pointer to non-constant data
var yb = Array(1,2,3) // non-constant pointer to non-constant data
For example, yb
means we can mutate both the address stored in yb
as well as the data pointed to by yb
:
yb = ya // mutating the pointer
yb(0) = 42 // mutating the pointed-to-data
Ideally, we strive for xa
usage, that is, for constant pointer to constant data. In functional programming, when we speak of immutability, we usually have this xa
situation in mind.
Upvotes: 3