Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

kotlin

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?

like image 584
LEMUEL ADANE Avatar asked Mar 22 '15 23:03

LEMUEL ADANE


1 Answers

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() 
like image 65
naixx Avatar answered Sep 19 '22 16:09

naixx