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

LEM*_*ANE 25 arrays kotlin

我有以下代码:

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)
}
Run Code Online (Sandbox Code Playgroud)

如果我称之为:

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

for (p2 in list) {
    p2.delete()
    p2.commit()
}
Run Code Online (Sandbox Code Playgroud)

它会给我错误:

For循环范围必须具有'iterator()'方法

我在这里错过了什么吗?

nai*_*ixx 46

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

for (p2 in list.orEmpty()) { ... }
Run Code Online (Sandbox Code Playgroud)

要么

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

    }
}
Run Code Online (Sandbox Code Playgroud)

或者你可以只返回一个空列表

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

  • 或者列出?.forEach {it.delete()...} (7认同)
  • `list?.forEach { ... }` 处理空值(如上所述,只需在其周围添加代码块) (2认同)

小智 5

尝试

for(p2 in 0 until list.count()) {
    ...
    ...
} 
Run Code Online (Sandbox Code Playgroud)