Kotlin: For-loop must have an iterator method - is

2020-04-01 08:43发布

问题:

I have the following code:

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-loop range must have an 'iterator()' method

Am I missing something here?

回答1:

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

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

or

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


回答2:

I also face this problem when I loop on some thing it is not an array.
Example

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)

    }
}

This is different case to this question but hope it help



标签: arrays kotlin