W3cubDocs

/Kotlin

orEmpty

Platform and version requirements: JVM (1.0), JS (1.0), Native (1.0)
fun <T> Collection<T>?.orEmpty(): Collection<T>

Returns this Collection if it's not null and the empty list otherwise.

import kotlin.test.*

fun main(args: Array<String>) {
//sampleStart
val nullCollection: Collection<Any>? = null
println(nullCollection.orEmpty()) // []

val collection: Collection<Char>? = listOf('a', 'b', 'c')
println(collection.orEmpty()) // [a, b, c]
//sampleEnd
}
Platform and version requirements: JVM (1.0), JS (1.0), Native (1.0)
fun <T> List<T>?.orEmpty(): List<T>

Returns this List if it's not null and the empty list otherwise.

import kotlin.test.*

fun main(args: Array<String>) {
//sampleStart
val nullList: List<Any>? = null
println(nullList.orEmpty()) // []

val list: List<Char>? = listOf('a', 'b', 'c')
println(list.orEmpty()) // [a, b, c]
//sampleEnd
}
Platform and version requirements: JVM (1.0), Native (1.3)
fun <reified T> Array<out T>?.orEmpty(): Array<out T>
Platform and version requirements: JS (1.1)
fun <T> Array<out T>?.orEmpty(): Array<out T>
For Common, JS, Native

Returns the array if it's not null, or an empty array otherwise.

For JVM

Returns the array if it's not null, or an empty array otherwise.

import kotlin.test.*

fun main(args: Array<String>) {
//sampleStart
val nullArray: Array<Any>? = null
println(nullArray.orEmpty().contentToString()) // []

val array: Array<Char>? = arrayOf('a', 'b', 'c')
println(array.orEmpty().contentToString()) // [a, b, c]
//sampleEnd
}
Platform and version requirements: JVM (1.0), JS (1.0), Native (1.0)
fun <K, V> Map<K, V>?.orEmpty(): Map<K, V>

Returns the Map if its not null, or the empty Map otherwise.

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

fun main(args: Array<String>) {
//sampleStart
val nullMap: Map<String, Any>? = null
println(nullMap.orEmpty()) // {}

val map: Map<Char, Int>? = mapOf('a' to 1, 'b' to 2, 'c' to 3)
println(map.orEmpty()) // {a=1, b=2, c=3}
//sampleEnd
}
Platform and version requirements: JVM (1.0), JS (1.0), Native (1.0)
fun <T> Set<T>?.orEmpty(): Set<T>

Returns this Set if it's not null and the empty set otherwise.

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