https://kotlinlang.org logo
#announcements
Title
# announcements
u

Uziel Sulkies

10/30/2019, 11:59 AM
I was just astonished to find out that Map.getValue(key) does not guarantee non-null value. If a map has explicit null value for a key, this method will return null !
🤯 1
Untitled
d

diesieben07

10/30/2019, 12:02 PM
Yes,
null
is still a value in the map.
u

Uziel Sulkies

10/30/2019, 12:06 PM
Hmmm... Now I understand that this if the map's type is <String, String?> the compiler treats the value as nullable. The problem is when a json map with null value is deserialized into Map<String, String> which is not type-safe. Then you can bypass the compiler's protection, and get an exception only when you try to something with the value, like using it as a constructor parameter of a non-nullable value. Then you'll get exception in Runtime.
d

diesieben07

10/30/2019, 12:08 PM
Yes, generics are erased. This is not limited to nullability. You can unsafely cast
Map<String, Any>
to
Map<String, String>
and then get an exception at runtime when you try to use the values as strings.
a

arekolek

10/31/2019, 11:04 AM
The problem is when a json map with null value is deserialized into Map<String, String> which is not type-safe.
I’ve seen that problem with Gson. On the other hand moshi-kotlin works with non-nullable types properly.
Although I’m not sure how that’s going to work with
Map
🤔
2 Views