I try to get the image url of the first object tha...
# stdlib
s
I try to get the image url of the first object that exist in the database based on a list of object ids. My current solution looks like the following:
Copy code
var 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:
Copy code
var imageUrl = ids.firstNotNullFlat {
  var item = database.getItemById(it)
  item?.imageUrl
}
s
A less imperative way would be to use a Sequence, map id to imageUrl, call firstOrNull to search for first not null
s
Like this?
Copy code
val 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?
s
I believe that is the general idea of sequences
Havent used them myself much
s
Smart sequences 💡 Thanks a lot, I haven't really used them myself too.
p
You need to call
firstOrNull { it != null }
. Alternatively you can write:
mapNotNull { ... }.firstOrNull()
s
@Pavlo Liapota thanks a lot