How do I initialize Kotlin's MutableList to empty MutableList?

后端 未结 3 2021
一整个雨季
一整个雨季 2020-12-02 05:29

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 some

相关标签:
3条回答
  • 2020-12-02 05:42

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

    val myList = mutableListOf<Kolory>() 
    // or more specifically use the helper for a specific list type
    val myList = arrayListOf<Kolory>()
    

    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 read-only, for example:

    val myList: List<Kolory> = ArrayList()
    
    0 讨论(0)
  • 2020-12-02 05:48

    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))
    
    0 讨论(0)
  • 2020-12-02 05:54

    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.

    0 讨论(0)
提交回复
热议问题