Mutable arrays with immutable elements

Let's take a look at how the concepts of mutable and immutable types work in an array. The array size is immutable in any case; once the array has been declared, the size of the array cannot be updated. Sometimes, however, things get confusing when it comes to reassigning the variable. To understand this concept, let's take an example. Just like other variables, arrays can be declared with the val and var keywords:

val immutableArray = arrayOf(1,2,3)
var mutableArray = arrayOf(1,2,3)

Both the immutableArray and mutableArray arrays are fixed in size, but the elements of each array are mutable and can be updated as many times as we want:

val immutableArray = arrayOf(1,2,3)
immutableArray.set(0,10)
immutableArray[1] = 20

var mutableArray = arrayOf(1,2,3)
mutableArray.set(0,10)
mutableArray[1] = 20

The only difference between these arrays is that immutableArray is declared with the val keyword. This means that this array cannot be reassigned:

fun mutableOrImmutable(){
val immutableArray = arrayOf(1,2,3)
immutableArray.set(0,10)
// immutableArray = arrayOf(5,6,7,8,9,10)

var mutableArray = arrayOf(1,2,3)
mutableArray.set(0,10)
mutableArray = immutableArray
}

mutableArray, however, can be reassigned as many times as we want.

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

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