```fun toMap(): Map<String, Double> = mapOf(...
# getting-started
h
Copy code
fun toMap(): Map<String, Double> = mapOf("key" to nullableDouble1, "key2" to nullableDouble2).filterValues { it != null }
complains that "expected
Map<String, Double>
but found `Map<String, Double?>`". Is there an easy way around this other than appending
as Map<String, Double>
?
s
You can do something like
.entries.mapNotNull { (k,v) -> v?.let {k to v}  }.toMap()
Unfortunately
.mapValuesNotNull()
does not exist
Or rather this does not exist yet:
h
I solved it by adding
.mapValues { it.value ?: 0.0 }
at the end
k
Maybe
.mapValues { it!! }
is safer.
h
I hate having
!!
in kotlin code
k
Then put the propesed function somewhere in your codebase.
?: 0
just hides the issue and you're back to not actually having null safety.
You've just replaced
null
with
0.0
.
h
yeah, but I just removed all null values in the filter statement before that
so that
mapValues
is just a dummy
(with a proper comment)
k
Yeah, and
.mapValues { it!! }
is a safer dummy that will throw if someone ever changes the map call.
h
good point
Weirdly it's
mapValues { it.value!! }
😱 1
k
Really?
Double
{{}}
?
h
😄 nope 🙂
Hah, I finally figured out how to do this properly.
Copy code
fun toMap(): Map<String, Double> = 
    mapOf("key" to 1.1, "key2" to null)
    .mapNotNull { it.value?.let { value -> it.key to value } }
    .toMap()
📆 1