vi0
vi0

Reputation: 350

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

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?

Upvotes: 1

Views: 108

Answers (0)

Related Questions