Casting to a mutable collection (such as MutableList
) should be avoided as it poses inherent safety risks. A common design
pattern in classes involves exposing read-only views of mutable collections as immutable collection instances to safeguard
them from external mutations. Kotlin adopts this approach to prevent crashes when dealing with Lists, Maps, etc., that must
remain unmodified. When this design pattern is circumvented through casting, it may succeed at runtime if the underlying
list isn't a Java immutable list implementation. However, doing so can lead to hard-to-track bugs and therefore, should
be avoided.
val list : List<Int> = getAList()
(list as MutableList).add(42)
Consider using toMutableLists()
instead.
val list : List<Int> = getAList()
val mutableList = list.toMutableList().add(42)