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 :
getOrNull()
: returns the element at specified index (if found) ornull
(if not found).getOrElse()
: returns the element at specified index (if found) or executes the given code block (if not found).
// 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 */