Why is getValue preferred over !! when retrieving from a Map (NoSuchElementException vs NullPointerException)?

44 views Asked by At

When in Map using the !! operator, SonarQube issues warning s6611 "Map" values should be accessed safely. One solution from Sonar is to use getValue, which will throw a NoSuchElementException if the key is not found.

val a = mapOf<Int, Map<String, String>>()
a[999]!!["x"]        // NullPointerException
a.getValue(999)["x"] // NoSuchElementException: Key 999 is missing in the map.

What is the benefit of NoSuchElementException other than reporting the value of a key that is not found?

0

There are 0 answers