https://kotlinlang.org logo
Title
h

henrik

11/22/2018, 8:56 AM
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

spand

11/22/2018, 9:14 AM
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

henrik

11/22/2018, 9:17 AM
I solved it by adding
.mapValues { it.value ?: 0.0 }
at the end
k

karelpeeters

11/22/2018, 9:31 AM
Maybe
.mapValues { it!! }
is safer.
h

henrik

11/22/2018, 9:32 AM
I hate having
!!
in kotlin code
k

karelpeeters

11/22/2018, 9:33 AM
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

henrik

11/22/2018, 9:34 AM
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

karelpeeters

11/22/2018, 9:34 AM
Yeah, and
.mapValues { it!! }
is a safer dummy that will throw if someone ever changes the map call.
h

henrik

11/22/2018, 9:35 AM
good point
Weirdly it's
mapValues { it.value!! }
😱 1
k

karelpeeters

11/22/2018, 9:39 AM
Really?
Double
{{}}
?
h

henrik

11/22/2018, 9:40 AM
😄 nope 🙂
Hah, I finally figured out how to do this properly.
fun toMap(): Map<String, Double> = 
    mapOf("key" to 1.1, "key2" to null)
    .mapNotNull { it.value?.let { value -> it.key to value } }
    .toMap()
📆 1