orEmpty

inline fun <T> Collection<T>?.orEmpty(): Collection<T>

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

Samples

import samples.*
import kotlin.test.*
fun main() { 
   //sampleStart 
   val nullCollection: Collection<Any>? = null
assertPrints(nullCollection.orEmpty(), "[]")

val collection: Collection<Char>? = listOf('a', 'b', 'c')
assertPrints(collection.orEmpty(), "[a, b, c]") 
   //sampleEnd
}

inline fun <T> List<T>?.orEmpty(): List<T>

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

Samples

import samples.*
import kotlin.test.*
fun main() { 
   //sampleStart 
   val nullList: List<Any>? = null
assertPrints(nullList.orEmpty(), "[]")

val list: List<Char>? = listOf('a', 'b', 'c')
assertPrints(list.orEmpty(), "[a, b, c]") 
   //sampleEnd
}

inline fun <K, V> Map<K, V>?.orEmpty(): Map<K, V>

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

Samples

import samples.*
import kotlin.test.*
import java.util.*
fun main() { 
   //sampleStart 
   val nullMap: Map<String, Any>? = null
assertPrints(nullMap.orEmpty(), "{}")

val map: Map<Char, Int>? = mapOf('a' to 1, 'b' to 2, 'c' to 3)
assertPrints(map.orEmpty(), "{a=1, b=2, c=3}") 
   //sampleEnd
}

inline fun <T> Set<T>?.orEmpty(): Set<T>

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


expect inline fun <T> Array<out T>?.orEmpty(): Array<out T>

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

actual inline fun <T> Array<out T>?.orEmpty(): Array<out T>

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

Samples

import samples.*
import kotlin.test.*
fun main() { 
   //sampleStart 
   val nullArray: Array<Any>? = null
assertPrints(nullArray.orEmpty().contentToString(), "[]")

val array: Array<Char>? = arrayOf('a', 'b', 'c')
assertPrints(array.orEmpty().contentToString(), "[a, b, c]") 
   //sampleEnd
}
actual inline fun <T> Array<out T>?.orEmpty(): Array<out T>

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

actual inline fun <T> Array<out T>?.orEmpty(): Array<out T>

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