【发布时间】:2017-04-02 15:34:50
【问题描述】:
我有一个返回List<Contact> 的方法(getContacts),我需要将此结果转换为MutableList<Contact>。目前我能想到的最好方法是这样的:
val contacts: MutableList<Contact> = ArrayList(presenter.getContacts())
有没有更惯用/“更少 Java”的方式来做到这一点?
【问题讨论】:
我有一个返回List<Contact> 的方法(getContacts),我需要将此结果转换为MutableList<Contact>。目前我能想到的最好方法是这样的:
val contacts: MutableList<Contact> = ArrayList(presenter.getContacts())
有没有更惯用/“更少 Java”的方式来做到这一点?
【问题讨论】:
如果要将List 或MutableList 转换为数组,也可以使用toTypedArray()
/**
* 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>
}
myMutableList.toTypedArray()
【讨论】:
如果你只想要 ArrayList,你可以创建自己的 Kotlin 扩展。
fun <T> List<T>.toArrayList(): ArrayList<T>{
return ArrayList(this)
}
然后你可以在你的应用程序中使用它
myList.toArrayList()
简单易行
【讨论】:
考虑使用toMutableList() 函数:
presenter.getContacts().toMutableList()
对于 stdlib 类型有 toMutableList() 扩展,可能需要转换为可变列表:Collection<T>、Iterable<T>、Sequence<T>、CharSequence、Array<T> 和原始数组。
【讨论】: