orEmpty
所在位置是kotlin.collections.orEmpty
,其相關用法介紹如下。
用法一
如果不是 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]
用法二
如果不是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]
用法三
如果不是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]
用法四
如果不是 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}
用法五
相關用法
- Kotlin orEmpty用法及代碼示例
- Kotlin associateBy用法及代碼示例
- Kotlin all用法及代碼示例
- Kotlin map用法及代碼示例
- Kotlin filterNot用法及代碼示例
- Kotlin reduceRight用法及代碼示例
- Kotlin Random.Default用法及代碼示例
- Kotlin Byte.inc用法及代碼示例
- Kotlin getValue用法及代碼示例
- Kotlin Double.dec用法及代碼示例
- Kotlin windowedSequence用法及代碼示例
- Kotlin contentToString用法及代碼示例
- Kotlin groupByTo用法及代碼示例
- Kotlin commonPrefixWith用法及代碼示例
- Kotlin MatchResult.Destructured用法及代碼示例
- Kotlin Delegates.notNull用法及代碼示例
- Kotlin ifBlank用法及代碼示例
- Kotlin filterNotTo用法及代碼示例
- Kotlin getOrPut用法及代碼示例
- Kotlin Triple.<init>用法及代碼示例
- Kotlin Duration.toString用法及代碼示例
- Kotlin windowed用法及代碼示例
- Kotlin indexOf用法及代碼示例
- Kotlin reduceIndexed用法及代碼示例
- Kotlin filterKeys用法及代碼示例
注:本文由純淨天空篩選整理自kotlinlang.org大神的英文原創作品 kotlin.collections.orEmpty。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。