In Kotlin, a list created using the listOf() function (which should be immutable) passes a type check against MutableList using the is operator.
Example:
fun main(args: Array<String>) {
val list = listOf("I'm immutable")
println(list is MutableList)
}
will print
true
Interestingly, an empty list created using listOf<String>() will fail the check and print false as it returns the singleton object EmptyList.
After some digging, it turns out that mutableListOf() creates a java.util.ArrayList whilst listOf() ends up creating a java.util.Arrays$ArrayList, but none of the classes involved implement MutableList, so why does a non-empty list still pass the type check against it? Hence, is there an alternative way of reliably checking if a list is mutable without having to check against it's actual implementation (is ArrayList etc.)?
Kotlin MutableList is an interface and generic collection of elements. MutableList interface is mutable in nature. It inherits form Collection<T> class. The methods of MutableList interface supports both read and write functionalities.
Since you are iterating through the whole list, simplest way would be to call clear method of MutableList after you process all items. Other option could be method remove to remove given element or removeAt to remove element at given index.
The method mutableListOf() returns an instance of MutableList Interface and takes the array of a particular type or mixed (depends on the type of MutableList instance) elements or it can be null also.
A generic ordered collection of elements that supports adding and removing elements.
The separation between List and MutableList is an illusion created by the Kotlin compiler. At runtime, Kotlin uses Java collection classes, which only have a single List interface containing both read and mutation methods. Compile-time references to List and MutableList are both compiled to java.util.List references. Therefore, it's not possible to detect whether a list is a MutableList at runtime.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With