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 =newArrayrings(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:
1
Hi array of Strings.
Understanding val and Mutability
Although val makes a variable immutable, it does not make the contents of an array immutable. You cannot reassignarrayOfStrings 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:
1
Bye array of Strings.
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.