Jan B.
Jan B.

Reputation: 6448

Shorten filter and map in Kotlin

From a list of nullable Transformation objects that contain a user I want the non-null IDs of non-null users. Is there a way to shorten this expression?

val list: List<Transformation> = ...
list.filter {t -> t.user!!.id !== null }.map { t -> t.user!!.id!! }

Upvotes: 0

Views: 970

Answers (2)

s1m0nw1
s1m0nw1

Reputation: 81889

You can use mapNotNull:

list.mapNotNull { t -> t.user?.id }

This will filter out all null users from list and also IDs (of non-null users) which are null.

Note that your usage of !! is not correct in this case. it will cause NullPointerExceptions for nulls in your list. You should have a look at how the nullability operators work in Kotlin: https://kotlinlang.org/docs/reference/null-safety.html

Upvotes: 10

Frank Neblung
Frank Neblung

Reputation: 3165

From your example code, it's not clear what's in the list. It does not seam to be a list of users, but a list of something, containing a user.

Given that

class User(val id: Int)

fun getIds(userList: List<User?>): List<Int> {
    return userList.filterNotNull().map { it.id }
}

or as an extension function:

fun List<User?>.getIds2() = filterNotNull().map { User::id }

Upvotes: 2

Related Questions