Thread
#stdlib
    Simon Schubert

    Simon Schubert

    2 years ago
    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:
    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:
    var imageUrl = ids.firstNotNullFlat {
      var item = database.getItemById(it)
      item?.imageUrl
    }
    s

    spand

    2 years ago
    A less imperative way would be to use a Sequence, map id to imageUrl, call firstOrNull to search for first not null
    Simon Schubert

    Simon Schubert

    2 years ago
    Like this?
    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

    spand

    2 years ago
    I believe that is the general idea of sequences
    Havent used them myself much
    Simon Schubert

    Simon Schubert

    2 years ago
    Smart sequences 💡 Thanks a lot, I haven't really used them myself too.
    Pavlo Liapota

    Pavlo Liapota

    2 years ago
    You need to call
    firstOrNull { it != null }
    . Alternatively you can write:
    mapNotNull { ... }.firstOrNull()
    Simon Schubert

    Simon Schubert

    2 years ago
    @Pavlo Liapota thanks a lot