【问题标题】:Kotlin - Most idiomatic way to convert a List to a MutableListKotlin - 将 List 转换为 MutableList 的最惯用方式
【发布时间】:2017-04-02 15:34:50
【问题描述】:

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

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

有没有更惯用/“更少 Java”的方式来做到这一点?

【问题讨论】:

    标签: android kotlin


    【解决方案1】:

    如果要将ListMutableList 转换为数组,也可以使用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()
    

    【讨论】:

      【解决方案2】:

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

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

      然后你可以在你的应用程序中使用它

      myList.toArrayList()
      

      简单易行

      【讨论】:

        【解决方案3】:

        考虑使用toMutableList() 函数:

        presenter.getContacts().toMutableList()
        

        对于 stdlib 类型有 toMutableList() 扩展,可能需要转换为可变列表:Collection&lt;T&gt;Iterable&lt;T&gt;Sequence&lt;T&gt;CharSequenceArray&lt;T&gt; 和原始数组。

        【讨论】:

        • 不仅适用于Collection,也适用于Iterable、Sequence、Arrays、CharSequence。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-01-31
        • 1970-01-01
        • 2017-06-24
        • 1970-01-01
        • 1970-01-01
        • 2019-11-07
        • 2013-02-17
        相关资源
        最近更新 更多