Kotlin:For 循环必须有一个迭代器方法——这是一个错误吗?

Kotlin: For-loop must have an iterator method - is this a bug?

我有以下代码:

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)
}

如果我这样称呼它:

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

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

它会给我错误:

For-loop range must have an 'iterator()' method

我是不是漏掉了什么?

您的 ArrayList 是可空类型。所以,你必须解决这个问题。有几种选择:

for (p2 in list.orEmpty()) { ... }

 list?.let {
    for (p2 in it) {

    }
}

或者您可以 return 一个空列表

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

当我在一些不是数组的东西上循环时,我也遇到这个问题。
例子

fun maximum(prices: Array<Int>){
    val sortedPrices = prices.sort()
    for(price in sortedPrices){ // it will display for-loop range must have iterator here (because `prices.sort` don't return Unit not Array)

    }
}

这个问题的情况不同,但希望对您有所帮助

这也可能发生在 Android 中,当您从共享首选项中读取并获取(可能)可为 null 的可迭代对象时,如 StringSet。即使您提供了默认值,编译器也无法确定返回值实际上永远不会为 null。我发现的唯一方法是使用 !! 运算符断言返回的表达式不为空,如下所示:

val prefs = PreferenceManager.getDefaultSharedPreferences(appContext)
val searches = prefs.getStringSet("saved_searches", setOf())!!
for (search in searches){
    ...
}

尝试

for(p2 in 0 until list.count()) {
    ...
    ...
}