Simon Schubert
12/12/2019, 12:06 PMvar ids = listOf("123", "456", ...)
var imageUrl = getFirstImageUrl(ids)
fun getFirstImageUrl(list: List<String>): String? {
list.forEach {
var item = database.getItemById(it)
if(item != null) {
return item.imageUrl
}
}
return null
}
Is there a better way to do it in kotlin? I could image a solution something like this:
var imageUrl = ids.firstNotNullFlat {
var item = database.getItemById(it)
item?.imageUrl
}
spand
12/12/2019, 12:10 PMSimon Schubert
12/12/2019, 12:21 PMval imageUrl = ids.asSequence().map { database.getItemById(it)?.imageUrl }.firstOrNull()
It returns the imageUrl
of the first found item in the database and stops iterating over the remaining ids right?spand
12/12/2019, 12:25 PMspand
12/12/2019, 12:25 PMSimon Schubert
12/12/2019, 12:30 PMPavlo Liapota
12/12/2019, 3:55 PMfirstOrNull { it != null }
.
Alternatively you can write:
mapNotNull { ... }.firstOrNull()
Simon Schubert
12/13/2019, 10:28 AM