使用mapTo为ArrayList赋值
以前我使用这个代码:
private val mItems = ArrayList<Int>() (1..item_count).mapTo(mItems) { it } /* mItems will be: "1, 2, 3, 4, 5, ..., item_count" */
现在,我正在使用一个类而不是Int
,但该类具有名称id
Int
成员。
class ModelClass(var id: Int = 0, var status: String = "smth")
那么我怎样才能用这个方法来以类似的方式填充ArrayList
呢?
//? private val mItems = ArrayList<ModelClass>() (1..item_count).mapTo(mItems) { mItems[position].id = it } // Something like this //?
从mapTo
文档 :
将给定的转换函数应用于原始集合的每个元素,并将结果附加到给定的目标。
因此,你只需要返回你想要的元素:
(1..item_count).mapTo(mItems) { ModelClass(it) }
如果你可以使用任何MutableList
(通常是ArrayList
或类似的):
val mItems1 = MutableList(item_count) { i -> i } val mItems2 = MutableList(item_count) { ModelClass(it) }