What is the getOrElse method of LinkedHashMap in Kotlin?
The getOrElse method can safely get the value of the key. The method provides a default value for the key when there is no mapping for a specific key present in the LinkedHashMap.
Syntax
fun <K, V> Map<K, V>.getOrElse(key: K,defaultValue: () -> V): V
Syntax of getOrElse method
Parameters
This method takes two arguments:
- The
keyfor which a value to be returned is passed as an argument. - The
default valuefunction. The value returned from that function will be returned as a result of the mapping if the passed key is not present.
Return value
This method returns the value associated with the key. If the mapping for the key is not present, the default value is returned.
fun main() {//create a new LinkedHashMap which can have integer type as key, and string type as valueval map: LinkedHashMap<Int, String> = linkedMapOf()// add two entriesmap.put(1, "one")map.put(2, "two")println("The map is : $map")// get value for key 1var value = map.getOrElse(1, {"Default"});println("getOrElse(1, {'Default'}) : $value")value = map.getOrElse(5, {"Default"});println("getOrElse(5, {'Default'}) : $value")}
Explanation
- Line 3: We create a new
LinkedHashMapobject namedmap. We use thelinkedMapOfmethod to create an emptyLinkedHashMap. - Lines 5 - 6: We add two new entries {1=one, 2=two} to the
mapusing theput()method. - Line 9: We use the
getOrElsemethod with the key1and the default value'Default'. In our case, there is a mapping for the key1, so the mapped valueOneis returned. - Line 11: We use the
getOrElsemethod with the key5and the default value'Default'. In our case, there is no mapping for the key5, so the default valueDefaultis returned.