W3cubDocs

/Kotlin

getOrElse

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

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

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

fun main(args: Array<String>) {
//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> List<T>.getOrElse(
    index: Int, 
    defaultValue: (Int) -> T
): T

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.

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

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.

© 2010–2017 JetBrains s.r.o.
Licensed under the Apache License, Version 2.0.
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/get-or-else.html