Kotlin-将列表转换为MutableList的最惯用方式 [英] Kotlin - Most idiomatic way to convert a List to a MutableList
问题描述
我有一个返回List<Contact>
的方法(getContacts
),我需要将此结果转换为MutableList<Contact>
.目前,我能想到的最好方法是这样的:
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())
是否有更惯用的/更少的Java"?做到这一点的方法?
Is there a more idiomatic/"less Java" way to do that?
推荐答案
Consider using the toMutableList()
function:
presenter.getContacts().toMutableList()
可能要转换为可变列表的stdlib类型具有toMutableList()
扩展名:Collection<T>
,Iterable<T>
,Sequence<T>
,CharSequence
,Array<T>
和原始数组.
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.
这篇关于Kotlin-将列表转换为MutableList的最惯用方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!