2015-03-22 13 views
7

Mam następujący kod:Kotlin: For-loop musi mieć metodę iteratora - czy to błąd?

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

Jeśli ja nazywam to tak:

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

for (p2 in list) { 
    p2.delete() 
    p2.commit() 
} 

To daje mi błąd:

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

jestem brakuje czegoś tutaj?

Odpowiedz

18

Twój ArrayList jest typu null. Musisz to rozwiązać. Istnieje kilka opcji:

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

lub

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

    } 
} 

czy można po prostu wrócić pustą listę

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

Alternatywnie Sprzedawców .forEach {it.delete() ...} –

+0

'list? .forEach {...}' obsługuje wartość zerową (jak wspomniano powyżej, po prostu dodając blok kodu wokół niej) –

Powiązane problemy