Kotlin Training Program

DOWNLOAD APP

FEEDBACK

Safe get()

List, Array

When trying to get an element at specified index, exception may be thrown if index is out of bounds. To avoid this exception, we can use the following function :

 // Syntax :
coll.getOrNull()
coll.getOrNull() ?: /* Default value */
coll.getOrElse() { /* Code to execute, return default value */ }
 

Example :

 fun main() {
    val nums = listOf(1, 2, 3)
    
    // typeof x = Int?
    val x = nums.getOrNull(3)
    
    // typeof y = Int (Default value provided)
    val y = nums.getOrNull(3) ?: -1
    
    // typeof z = Int (Default value provided)
    val z = nums.getOrElse(3) {
        println("z: nums[$it] not found!")
        0 // Default value
    }
    
    println("""
        x = $x
        y = $y
        z = $z
    """.trimIndent())
}

/* Output :
z: nums[3] not found!
x = null
y = -1
z = 0 */
 

Map

When looking up for a key in Map, we get a nullable result. The returned value is null when given key is not found in the map :

 val map = mapOf(
    "A" to 1, "B" to 2, "C" to 3
)
val a = map["A"] // Type : Int?
 

To avoid nullable return type & properly handle not found case, we can use the following functions :

 map.getOrDefault(/* key */, /* Default Value */)
map.getOrElse(/* key */) { /* Code to execute, return default value */ }
 

Example :

 fun main() {
    val map = mapOf(
        "A" to 1, "B" to 2, "C" to 3
    )
    
    val a = map["A"] // Type : Int?
    
    val b = map.getOrDefault("B", -1) // Type : Int
    
    val d = map.getOrElse("D") {
        println("D not found!")
        -1 // Default value
    }
    
    println("""
        a = $a
        b = $b
        d = $d
    """.trimIndent())
}

/* Output :

D not found!
a = 1
b = 2
d = -1 */