In Kotlin, What's the best way to iterate through an Android Cursor object and put the results into a list?

我的自动转换Java:

val list = ArrayList<String>()
while (c.moveToNext()) {
    list.add(getStringFromCursor(c))
}

Is there a more idiomatic way? In particular, can it be done in a single assignment of a read-only list? E.g....

val list = /*mystery*/.map(getStringFromCursor)

...或某种其他布置,其中列表被分配为完全形成的.

推荐答案

This is what I went with in the end, using kotlin.sequences.generateSequence...

val list = generateSequence { if (c.moveToNext()) c else null }
        .map { getStringFromCursor(it) }
        .toList()

我的第一次try 稍微短了一点:

val list = (1 .. c.count).map {
    c.moveToNext()
    getStringFromCursor(c)
}

Both versions rely on the cursor initially being positioned before the first record (as a new cursor is). The second would throw if that wasn't the case, while the first would return a shorter list.

Kotlin相关问答推荐

有什么原因,我得到一个空相关的错误在这个代码

用普通Kotlin理解Gradle的Kotlin DSL'""

Kotlin中的增广赋值语句中的难以理解的错误

为什么在Spring中,对事务性方法调用的非事务方法调用仍然在事务中运行?

在构造函数中创建内部类实例时,只能使用包含类的接收器调用内部类的构造函数

如何在 kotlin 中的数据类中为变量提供多种类型

使用调度程序运行异步 Kotlin 代码

如何获取@JsonProperty 名称列表?

使用启动或使用 coroutineScope 启动协程之间的区别

内容更改后的 var 重新计算

有没有一种简单的方法可以将数组/列表中的每个元素相互相乘 - Kotlin?

从 HashMap 检索时的 NPE,即使 containsKey() 在多线程环境中返回 true

Kotlin:如何使用第一个参数的默认值进行函数调用并为第二个参数传递一个值?

ActivityOptions.makeSceneTransitionAnimation 在具有多个视图的 kotlin 中不起作用

如何在 Spring WebFlux 的响应正文中流式传输二进制数据

在用Kotlin编写的Android库公共API中处理R8+JvmStatic Annotation+Lambda

未找到导入 kotlinx.coroutines.flow.*

递归方法调用在 kotlin 中导致 StackOverFlowError 但在 java 中没有

我应该在哪里调用 MobileAds.initialize()?

Kotlin:获取文件的扩展名,例如.txt