13

I was using someMap.get(someKey) in my code, which gave me an error saying Please use !! or ?. When I used someMap.getValue(someKey), that error disappeared.

Can someone explain why we have 2 seemingly similar looking (but weirdly different) get function in Map class?

UPDATE

I guess it has something to do with exception, that getValue throws exception. But isnt it true that Kotlin doesnt have any exception throwing?

2

1 Answer 1

21

In Kotlin they provide both methods for Map. get(key) returns the value if it exists or returns null if it doesn't, hence the nullable type. getValue(key) either returns the value for the key or throws an Exception if the key does not exist: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/get-value.html

If you are sure your map will contain the key, you can avoid using the nullable variant and use getValue(); if you don't know what the map contains, then use get().

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.