Kotlin: For-loop must have an iterator method - is that a mistake?

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 it this:

 var list : ArrayList<Person>? = p1.findSomeLikeThis() for (p2 in list) { p2.delete() p2.commit() } 

This would give me an error:

The for loop interval must have the 'iterator ()' method

Did I miss something?

+7
arrays kotlin
source share
1 answer

Your ArrayList is of type NULL. So you have to solve 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() 
+18
source share

All Articles