Joshua Hansen
01/16/2024, 10:11 PMMap<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.
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>
Joshua Hansen
01/16/2024, 10:16 PMDaniel Pitts
01/17/2024, 2:08 AMval 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()
Shawn
01/17/2024, 2:30 AMkey?.to(value)
but otherwise yeah, I think that's the move until they add a dedicated method to the stdlibDaniel Pitts
01/17/2024, 3:26 AM?.to
. To be honest, I let github CoPilot write that bit for me. 😁ephemient
01/17/2024, 4:46 AMbuildMap { for ((key, value) in map) put(key ?: continue, value) }
Klitos Kyriacou
01/17/2024, 8:51 AMcontinue
there!Daniel Pitts
01/17/2024, 4:47 PM@Suppress("UNCHECKED_CAST")
val result = (myMap - null) as Map<String, Int>
Daniel Pitts
01/17/2024, 4:52 PM@Suppress("UNCHECKED_CAST")
fun <K : Any, V> Map<K?, V>.onlyNonNullKeys(): Map<K, V> = (this - null) as Map<K, V>