Converting a list of IDs to a list of objects

Suppose you have a third-party API that returns a list of user IDs and another one that returns the user object given that ID. Stubbed version of these might look something like this:

data class User(val id: String, val fullName: String?)

fun getUserIds() = listOf("mike", "peter", "unknown")

fun getUser(id: String) = when (id) {
  "mike" -> User(id, "Mike Gouline")
  "peter" -> User(id, "Peter Smith")
  else -> null
}

If you want to return a list of all users, you can do it in one line:

val users = getUserIds().map { getUser(it) }

As you may have noticed, there’s no “unknown” user so it evaluates to null. If you’re only interested in existing users, that’s easy to fix:

val users = getUserIds().map { getUser(it) }.filterNotNull()

“`

This filterNotNull() is a nice shortcut for the more explicit filter { it != null }.

Leave a Reply

Your email address will not be published. Required fields are marked *