Sunday 17 October 2021

Kotlin getOrElse & getOrPut

 getOrElse: 

This provides safe access to elements of a collection. It takes an index and a function that provides the default value in cases when the index is out of bound.

getOrPut: 

This returns the value of the key.  If the key is not found in the map, calls the default value function, puts its result into the map under the given key and returns value of the same.

Code Snippet:

    data class Header(val heading: String, val subHeading: String)    

    val items = listOf("AAA", "BBB", "CCC", "DDD")
    val itemMap = mutableMapOf("x" to "AAA", "y" to "BBB")

    val header = listOf(
        Header("Heading1", "SubHeading1"), Header("Heading2", "SubHeading2")
    )

    println("Item at index 2 ${items.getOrElse(2) { "NA" }}")
    println("Item at index 4 ${items.getOrElse(4) { "NA" }}")
    println("Header at index 1 ${header.getOrElse(1) { "NA" }}")
    println("Header at index 2 ${header.getOrElse(2) { "NA" }}")
    
    println("Map Data: $itemMap")
    println("Map Key x ${itemMap.getOrElse("x") { "NA" }}")
    println("Map Key z ${itemMap.getOrElse("z") { "NA" }}")
    
    println("Map Key x ${itemMap.getOrPut("x") { "XXX" }}")
    println("Map Key z ${itemMap.getOrPut("z") { "ZZZ" }}")

    // Remove Map Key "x"
    itemMap.remove("x")

    println("Refreshed Map Data: $itemMap")
    println("Map Key x ${itemMap.getOrPut("x") { "AAA" }}")
    println("Refreshed Map Data: $itemMap")

Output:

Item at index 2 CCC
Item at index 4 NA
Header at index 1 Header(heading=Heading2, subHeading=SubHeading2)
Header at index 2 NA
Map Data: {x=AAA, y=BBB}
Map Key x AAA
Map Key z NA
Map Key x AAA
Map Key z ZZZ
Refreshed Map Data: {y=BBB, z=ZZZ}
Map Key x AAA
Refreshed Map Data: {y=BBB, z=ZZZ, x=AAA}

Happy Coding :-)