2015-03-22 11 views
7

Aşağıdaki kod var: Böyle ararsamKotlin: For döngüsü bir yineleyici yönteme sahip olmalı - bu bir hata mı?

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

:

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

Burada bir şey eksik:

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

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

Bana hatayı verecek?

cevap

18

Sizin ArrayList'unuz null tipidir. Yani, bunu çözmelisin. Birkaç seçenek vardır:?

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

veya

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

    } 
} 

ya da sadece boş bir liste

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

listelemek dönebilirsiniz .forEach {it.delete() ...} –

+0

'list? .forEach {...}' null (yukarıda belirtildiği gibi, sadece kod bloğunu ekleyerek) –

İlgili konular