https://kotlinlang.org logo
#getting-started
Title
# getting-started
h

hfhbd

02/19/2022, 12:47 PM
Copy code
kt
val m: Map<String, Int> = mapOf("a" to 42, "b" to null).filterValues { it != null }
Any possibility to infer the not null type by the compiler? Workaround is a manual cast
s

Sam

02/19/2022, 12:56 PM
This question comes up a lot, I don't know of any better workaround. I'd just do the manual cast, but hide it inside an extension function.
v

Vampire

02/19/2022, 12:59 PM
Just that there are no null values does not mean you don't get null returned. Ask for a key not present in the map. ;-)
s

Sam

02/19/2022, 1:02 PM
Right, but that's why
Map.get
is defined to return
V?
, not `V`: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-map/get.html
So there is a meaningful distinction between a
Map<String, Int>
and a
Map<String, Int?>
👍
I guess a good example would be when you're iterating the map entries. If you know that the values are non-null, then you know that no entry will have a null value.
v

Vampire

02/19/2022, 1:07 PM
Ah, that, yeah, right
7 Views