As we know the List in Kotlin is immutable i.e. you can't do add and remove as below.
class TempClass {
var myList: List<Int>? = null
fun doSomething() {
myList = ArrayList<Int>()
myList!!.add(10)
myList!!.remove(10)
}
}
But if we cast it to ArrayList as below, the add and remove works.
class TempClass {
var myList: List<Int>? = null
fun doSomething() {
myList = ArrayList<Int>()
(myList!! as ArrayList).add(10)
(myList!! as ArrayList).remove(10)
}
}
I just thought this is odd, as myList is really a List, which is suppose to be immutable. And casting it, allow it to be altered.
Is what done above (casting to Array and modify the content) legitimate, or the language need to improve to disallow that?
MutableList
, a super type ofArrayList
ArrayList<Int>().apply { add(10) }
or even better just use the built-in factory functions likelistOf(10)
.Iterator
recieved from a list, asubList
from a list, aentrySet
from a map and more. See: stackoverflow.com/a/38002121/3679676 ... you cannot cast around it, nor any other collection it returns, they are truly protected.