gpt4 book ai didi

arraylist - 使用 mapTo 为 ArrayList 赋值

转载 作者:行者123 更新时间:2023-12-04 02:09:00 26 4
gpt4 key购买 nike

之前我使用的是这段代码:

private val mItems = ArrayList<Int>()
(1..item_count).mapTo(mItems) { it }

/*
mItems will be: "1, 2, 3, 4, 5, ..., item_count"
*/

现在,我正在使用一个类而不是 Int,但是该类有一个名为 idInt 成员。

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 documentation :

Applies the given transform function to each element of the original collection and appends the results to the given destination.

因此,你只需要返回你想要的元素:

(1..item_count).mapTo(mItems) { ModelClass(it) }

关于arraylist - 使用 mapTo 为 ArrayList 赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46198280/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com