How do I initialize Kotlin's MutableList to em

2019-01-10 08:03发布

问题:

Seems so simple, but, how do I initialize Kotlin's MutableList to empty MutableList?

I could hack it this way, but I'm sure there is something easier available:

var pusta: List<Kolory> = emptyList()
var cos: MutableList<Kolory> = pusta.toArrayList()

回答1:

You can simply write:

val mutableList = mutableListOf<Kolory>()

This is the most idiomatic way.

Alternative ways are

val mutableList : MutableList<Kolory> = arrayListOf()

or

val mutableList : MutableList<Kolory> = ArrayList()

This is exploiting the fact that java types like ArrayList are implicitly implementing the type MutableList via a compiler trick.



回答2:

Various forms depending on type of List, for Array List:

val myList = arrayListOf<Kolory>()
// same as
val myList: MutableList<Kolory> = arrayListOf()

For LinkedList:

val myList = linkedListOf<Kolory>()
// same as
val myList: MutableList<Kolory> = linkedListOf()

For other list types, will be assumed Mutable if you construct them directly:

val myList = ArrayList<Kolory>()
// or
val myList = LinkedList<Kolory>()

This holds true for anything implementing the List interface (i.e. other collections libraries).

No need to repeat the type on the left side if the list is already Mutable. Or only if you want to treat them as readonly, for example:

val myList: List<Kolory> = ArrayList()


回答3:

I do like below to :

var book: MutableList<Books> = mutableListOf()

/** Returns a new [MutableList] with the given elements. */

public fun <T> mutableListOf(vararg elements: T): MutableList<T>
    = if (elements.size == 0) ArrayList() else ArrayList(ArrayAsCollection(elements, isVarargs = true))


标签: kotlin