orEmpty所在位置是kotlin.collections.orEmpty,其相關用法介紹如下。

用法一

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

如果不是 null 則返回數組,否則返回空數組。

例子:

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
}

輸出:

[]
[a, b, c]

用法二

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

如果不是null,則返回此集合,否則返回空列表。

例子:

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
}

輸出:

[]
[a, b, c]

用法三

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

如果不是null,則返回此列表,否則返回空列表。

例子:

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
}

輸出:

[]
[a, b, c]

用法四

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

如果不是 null 則返回 Map ,否則返回空的 Map

例子:

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
}

輸出:

{}
{a=1, b=2, c=3}

用法五

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

如果不是null,則返回此 Set,否則返回空集。