我有以下代码:

public fun findSomeLikeThis(): ArrayList<T>? {
    val result = Db4o.objectContainer()!!.queryByExample<T>(this as T) as Collection<T>
    if (result == null) return null
    return ArrayList(result)
}

If I call this like:

var list : ArrayList<Person>? = p1.findSomeLikeThis()

for (p2 in list) {
    p2.delete()
    p2.commit()
}

It would give me the error:

For循环范围必须有一个"iterator()"方法

我错过什么了吗?

推荐答案

Your ArrayList is of nullable type. So, you have to resolve this. There are several options:

f或 (p2 in list.或Empty()) { ... }

 list?.let {
    f或 (p2 in it) {

    }
}

或 you can just return an empty list

public fun findSomeLikeThis(): List<T> //Do you need mutable ArrayList here?
    = (Db4o.objectContainer()!!.queryByExample<T>(this as T) as Collection<T>)?.toList().或Empty()

Kotlin相关问答推荐

Lambda和普通Kotlin函数有什么区别?

在KMP中使用koin将来自Android的上下文注入到SQLDelight Driver中

在Kotlin Jetpack中重用下拉菜单

Kotlin是否针对范围和进度优化sum()?

如何在Docker中使用Selenium和chromedriver?

如何通过更改现有数据类型来执行Android房间数据库迁移?

为什么 <= 可以应用于 Int 和 Long,而 == 不能?

如果不在可组合函数中,如何获取 stringResource

高效匹配两个 Flux

我们应该在 Effect 和 Either 之间 Select 哪个作为我们业务服务的返回类型?

如何从 kotlin 中的数据类访问 val?

如何使用 Android CameraX 自动对焦

内联函数导致单元测试代码覆盖率报告出错

Kotlin 语言是如何用 Kotlin 编写的?

片段内的 Kotlin 按钮 onClickListener 事件

更新到版本4.10.1/4.10.2后 Gradle 同步失败

在调用Kotlin数据类中的超类构造函数之前访问函数

Kotlin 的 Double.toInt() 中使用了哪种方法,舍入还是截断?

任何处理器都无法识别以下选项:'[kapt.kotlin.generated, room.incremental]'

Kotlin flatMap - map