Kotlin - 将List转换为MutableList的最常用方法

时间:2016-11-18 17:33:54

标签: android kotlin

我有一个返回List的方法(getContacts),我需要将此结果转换为MutableList。目前我能想到的最佳方式是:

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

是否有更惯用/“更少Java”的方法呢?

3 个答案:

答案 0 :(得分:77)

考虑使用toMutableList()功能:

presenter.getContacts().toMutableList()

stdlib类型有toMutableList()个扩展名,可能要转换为可变列表:Collection<T>Iterable<T>Sequence<T>CharSequenceArray<T>和原始数组。

答案 1 :(得分:0)

如果只需要ArrayList,则可以创建自己的Kotlin扩展。

SELECT row_name, seq, data 
FROM 
(
    SELECT *, 
    ROW_NUMBER() OVER (PARTITION BY row_name ORDER BY seq DESC) RN
    FROM your_table
)A
WHERE RN = 1

然后您可以在应用程序中使用它,例如

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

简单易用

答案 2 :(得分:0)

如果要将toTypedArray()List转换为Array,也可以使用MutableList

/**
 * 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()