I try to have a deep understanding of collection in Kotlin. I failed keep mutability of List when doing that:
val intsA = arrayListOf(1, 2, 3)
val intsB: List<Int> = intsA
intsA.add(4)
println("intsA = $intsA && intsB = $intsB")
resulting:
intsA = [1, 2, 3, 4] && intsB = [1, 2, 3, 4]
Yes I know I am passing the reference and I could do it more safely by doing:
val intsB: List<Int> = intsA.toList()
still I do not really understand what is happening behind the scene? Why the default casting in Kotlin is not to done more safely? Because it can be a bit dangerous to have that piece of code somewhere in code and later on use it thinking that it is immutable like here:
fun main(args: Array<String>) {
val intsA = arrayListOf(1)
val intsB: List<Int> = intsA
val myClass = MyClass(intsB)
intsA.add(2)
println("intsA = $intsA && intsB = $intsB && myClass = $myClass")
}
class MyClass(val list: List<Int>){
override fun toString(): String {
return "MyClass(list=$list)"
}
}
resulting:
intsA = [1, 2] && intsB = [1, 2] && myClass = MyClass(list=[1, 2])