Search code examples
kotlinarraylist

Initialize new arraylist with (custom) items in one line in Kotlin


In Kotlin I created an extension function to initialise a new ArrayList with custom items, like this:

fun <T> arrayListFrom(vararg item: T): ArrayList<T> {
    return item.toMutableList() as ArrayList<T>
}

In this way I can easily create an arraylist like this

arrayListFrom(MyCustomItem(1), MyCustomItem(2))

... without creating a new-empty one, and adding all elements to it one by one

Kotlin has so many useful functions for collections, I cannot imagine I need this extension for easy arrayList initialisation, but couldn't find another simple way. Am I missing out on some useful Kotlin function here?


Solution

  • arrayListOf(items), documentation here.

    So you can just do

    arrayListOf(MyCustomItem(1), MyCustomItem(2))