Kotlin - Most idiomatic way to convert a List to a MutableList

痴心易碎 提交于 2020-08-22 07:09:36

问题


I have a method (getContacts) that returns a List<Contact> and I need to convert this result to a MutableList<Contact>. Currently the best way I can think of doing it is like this:

val contacts: MutableList<Contact> = ArrayList(presenter.getContacts())

Is there a more idiomatic/"less Java" way to do that?


回答1:


Consider using the toMutableList() function:

presenter.getContacts().toMutableList()

There are toMutableList() extensions for the stdlib types that one might want to convert to a mutable list: Collection<T>, Iterable<T>, Sequence<T>, CharSequence, Array<T> and primitive arrays.




回答2:


If you only wants ArrayList, you can create your own Kotlin extension.

fun <T> List<T>.toArrayList(): ArrayList<T>{
    return ArrayList(this)
}

Then you can use it in your application like

myList.toArrayList()

Simple and easy




回答3:


You can also use toTypedArray() if you want to convert a List or MutableList to Array

/**
 * Returns a *typed* array containing all of the elements of this collection.
 *
 * Allocates an array of runtime type `T` having its size equal to the size of this collection
 * and populates the array with the elements of this collection.
 * @sample samples.collections.Collections.Collections.collectionToTypedArray
 */
@Suppress("UNCHECKED_CAST")
public actual inline fun <reified T> Collection<T>.toTypedArray(): Array<T> {
    @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
    val thisCollection = this as java.util.Collection<T>
    return thisCollection.toArray(arrayOfNulls<T>(0)) as Array<T>
}

Example

myMutableList.toTypedArray()


来源:https://stackoverflow.com/questions/40682918/kotlin-most-idiomatic-way-to-convert-a-list-to-a-mutablelist

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!