I am learning kotlin concepts and had the following question when I was going through the topic Arrays.
I created an empty
val empty = arrayOf<Int>()
empty[0] = 2
So the above code will fail and cause ArrayIndexOutOfBoundsException which makes sense because the size of an array cannot be changed and since the array was initialized with no size it is treated as an empty array.
Here is where i thought this gets interesting
var emptyArray = arrayOf<Int>()
emptyArray += 1
emptyArray += 2
The above code doesn't fail and when i print the items I am getting the results back. I am assuming there is something going on when trying to add an element to an index versus adding it directly but I couldn't find any documentation that explains what is going on under the hood. Can someone please explain
kotlin.collectionshas a plus operator for Arrays that return an array containing the original array plus the new element. And since you madeemptyArrayavarit's possible to reassign this new array toemptyArray.