What's the best way to take a `Map<String?, Int...
# getting-started
j
What's the best way to take a
Map<String?, Int>
and convert it to
Map<String, Int>
? I tried
filterKeys { it != null }
but the compiler doesn't seem to be smart enough to change the resulting type, so I have to cast after filtering.
Copy code
val myMap: Map<String?, Int> = mapOf(
    null to 0,
    "one" to 1,
    "two" to 2,
)

val withoutNullKeys = myMap.filterKeys { it != null } // Still is Map<String?, Int>
Looks like there's an issue for this. https://youtrack.jetbrains.com/issue/KT-4734
d
Not the prettiest work around, but you could do:
Copy code
val map = mapOf(
        null to 0,
        "One" to 1,
        "Two" to 2,
    )
    val result: Map<String, Int> = map.mapNotNull { (key, value) ->
        key?.let { key to value }
    }.toMap()
s
could simplify that to
key?.to(value)
but otherwise yeah, I think that's the move until they add a dedicated method to the stdlib
d
Good call on the
?.to
. To be honest, I let github CoPilot write that bit for me. 😁
e
build the map directly, skipping the intermediate list of pairs
Copy code
buildMap { for ((key, value) in map) put(key ?: continue, value) }
👍 2
k
Clever use of
continue
there!
2
d
Or, just tell the compiler its wrong:
Copy code
@Suppress("UNCHECKED_CAST")
val result = (myMap - null) as Map<String, Int>
Or more generally:
Copy code
@Suppress("UNCHECKED_CAST")
fun <K : Any, V> Map<K?, V>.onlyNonNullKeys(): Map<K, V> = (this - null) as Map<K, V>