Using the not-null assertion operator (!!
) along with the index operator []
or the .get()
method of a map type can result in a NullPointerException
if the key is not present in the map.
This is because Map.get()
returns null
if the key is not found.
By using the not-null assertion operator, you are explicitly telling the compiler that the result will never be null
, which can lead to a runtime exception if the assumption is incorrect.
To fix this issue we can use methods like map.getValue()
, map.getOrDefault()
, map.getOrElse()
, or just index the map with []
without also coercing the value to be non-null.
val value = map["nonExistentKey"]!!
val prop = value.someProperty // This will raise a `NullPointerException`
val value = map["nonExistentKey"]
val prop = value?.someProperty