Kotlin:For循环必须具有迭代器方法-这是一个错误吗? [英] Kotlin: For-loop must have an iterator method - is this a bug?

查看:635
本文介绍了Kotlin:For循环必须具有迭代器方法-这是一个错误吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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范围必须具有'iterator()'方法

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

我在这里想念东西吗?

推荐答案

您的ArrayList是可为空的类型.因此,您必须解决此问题.有几种选择:

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

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

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

    }
}

或者您可以返回一个空列表

or 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().orEmpty()

这篇关于Kotlin:For循环必须具有迭代器方法-这是一个错误吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆