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

Time:09-24

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?

CodePudding user response:

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.

CodePudding user response:

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() }
  • Related