Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: Map.get(key) vs Map.getValue(key)

Tags:

kotlin

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?

like image 432
Dhruv Chadha Avatar asked Jan 25 '26 01:01

Dhruv Chadha


1 Answers

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().

like image 90
Stefan Zhelyazkov Avatar answered Jan 26 '26 23:01

Stefan Zhelyazkov