Note: This post was created awhile back on another platform (Tumblr) and I migrated to my current one.
Array Initialization
Using new Array
Constructor
1
2
3
|
val arrayOfStrings = new Arrayrings(0) = "Hi"
arrayOfStrings(1) = " array"
arrayOfStrings(2) = " of Strings.\n"
|
Using Array
Factory Method
1
|
val arrayOfStrings = Array("Hi", " array", " of Strings.\n")
|
Printing Array Elements
1
2
|
for (i <- 0 to 2)
print(arrayOfStrings(i))
|
Output:
Understanding val
and Mutability
Although val
makes a variable immutable, it does not make the contents of an array immutable. You cannot reassign arrayOfStrings
to a new array, but you can modify its elements:
1
2
3
|
arrayOfStrings(0) = "Bye"
for (i <- 0 to 2)
print(arrayOfStrings(i))
|
Output:
Why Does This Happen?
Even though val
prevents reassignment of the variable, it does not make the object it points to immutable. The array itself remains mutable, meaning its elements can be modified. However, you cannot assign arrayOfStrings
to a completely new array.