Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

listOf() returns MutableList

Tags:

java

kotlin

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.)?

like image 870
Joel Evans Avatar asked Sep 30 '18 17:09

Joel Evans


People also ask

What is MutableList?

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.

How do I remove an item from MutableList Kotlin?

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.

Can MutableList be null?

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.

Is MutableList ordered?

A generic ordered collection of elements that supports adding and removing elements.


1 Answers

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.

like image 172
yole Avatar answered Oct 20 '22 18:10

yole