Light Yagami
Light Yagami

Reputation: 1043

How can I create a Map with non-null values from a set of nullable items in Kotlin?

In the Kotlin code, I want to add two fields to the map like this:

val myMap: Map<Type, List<Parameter>> = mapOf(
    Pair(Type.POST, request.postDetails.postParameters),//postDetails can be nullable
    Pair(Type.COMMENT, request.commentDetails.commentParameters)//commentDetails can be nullable
)

The above code is showing error at postDetails.postParameters and commentDetails.commentParameters because they can be nullable.

How can I create a map inplace like this instead of creating a variable and updating it where I want to keep the pair only in the case the value is not null?

Upvotes: 1

Views: 397

Answers (2)

Light Yagami
Light Yagami

Reputation: 1043

One way I found out without adding a lot of extra code would be to add code to add emptyList in the case it is null and remove them later.

Something like this:

val myMap: Map<Type, List<Parameter>> = mapOf(
    Pair(Type.POST, request.postDetails?.postParameters ?: listOf()),
    Pair(Type.COMMENT, request.commentDetails?.commentParameters ?: listOf())//commentDetails can be nullable
).filter{ it.value.isNotEmpty() }

Upvotes: 0

Sweeper
Sweeper

Reputation: 271040

I would just write my own factory methods for it, and call these methods instead.

fun <K, V> mapOfNullableValues(vararg pairs: Pair<K, V?>): Map<K, V> =
    pairs.mapNotNull { (k, v) ->
        if (v != null) k to v else null
    }.toMap()

fun <K, V> mutableMapOfNullableValues(vararg pairs: Pair<K, V?>): MutableMap<K, V> =
    pairs.mapNotNull { (k, v) ->
        if (v != null) k to v else null
    }.toMap(mutableMapOf())

By writing your own factory methods, you get to work with an array of Pairs, which is way easier than modifying the use site in place.

Note that compared to the built in builders, these methods create an extra list.

Upvotes: 4

Related Questions