getOrElse

inline fun <K, V> Map<K, V>.getOrElse(key: K, defaultValue: () -> V): V(source)

Returns the value for the given key, or the result of the defaultValue function if there was no entry for the given key.

Since Kotlin

1.1

Samples

import kotlin.test.*
import java.util.*

fun main() { 
   //sampleStart 
   val map = mutableMapOf<String, Int?>()
println(map.getOrElse("x") { 1 }) // 1

map["x"] = 3
println(map.getOrElse("x") { 1 }) // 3

map["x"] = null
println(map.getOrElse("x") { 1 }) // 1 
   //sampleEnd
}
inline fun <K, V> Map<K, V>.getOrElse(key: K, defaultValue: () -> V): V(source)

Returns the value for the given key, or the result of the defaultValue function if there was no entry for the given key.

Since Kotlin

1.0

Samples

import kotlin.test.*
import java.util.*

fun main() { 
   //sampleStart 
   val map = mutableMapOf<String, Int?>()
println(map.getOrElse("x") { 1 }) // 1

map["x"] = 3
println(map.getOrElse("x") { 1 }) // 3

map["x"] = null
println(map.getOrElse("x") { 1 }) // 1 
   //sampleEnd
}

inline fun <T> Array<out T>.getOrElse(index: Int, defaultValue: (Int) -> T): T(source)
inline fun ByteArray.getOrElse(index: Int, defaultValue: (Int) -> Byte): Byte(source)
inline fun ShortArray.getOrElse(index: Int, defaultValue: (Int) -> Short): Short(source)
inline fun IntArray.getOrElse(index: Int, defaultValue: (Int) -> Int): Int(source)
inline fun LongArray.getOrElse(index: Int, defaultValue: (Int) -> Long): Long(source)
inline fun FloatArray.getOrElse(index: Int, defaultValue: (Int) -> Float): Float(source)
inline fun DoubleArray.getOrElse(index: Int, defaultValue: (Int) -> Double): Double(source)
inline fun BooleanArray.getOrElse(index: Int, defaultValue: (Int) -> Boolean): Boolean(source)
inline fun CharArray.getOrElse(index: Int, defaultValue: (Int) -> Char): Char(source)

Returns an element at the given index or the result of calling the defaultValue function if the index is out of bounds of this array.

Since Kotlin

1.0

inline fun <T> List<T>.getOrElse(index: Int, defaultValue: (Int) -> T): T(source)

Returns an element at the given index or the result of calling the defaultValue function if the index is out of bounds of this list.

Since Kotlin

1.0