Spec-Zone.ru › Kotlin 2

илипустое значение

kotlin-stdlib/kotlin.collections/orEmpty

Требования к платформе и версии: Common (1.0)

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

Возвращает эту коллекцию, если она не null, иначе — пустой список.

Примеры

import kotlin.math.*
import kotlin.test.*

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

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

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

Возвращает этот список, если он не null, иначе — пустой список.

Примеры

import kotlin.math.*
import kotlin.test.*

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

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

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

Возвращает Map, если она не null, иначе — пустую Map.

Примеры

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

fun main() { 
   //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
}

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

Возвращает это множество, если оно не null, иначе — пустое множество.

Примеры

import kotlin.math.*
import kotlin.test.*

fun main() { 
   //sampleStart 
   val nullSet: Set<Any>? = null
println(nullSet.orEmpty()) // []

val set: Set<Char>? = setOf('a', 'b', 'c')
println(set.orEmpty()) // [a, b, c] 
   //sampleEnd
}

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

Возвращает массив, если он не null, иначе — пустой массив.

Примеры

import kotlin.test.*

fun main() { 
   //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
}

Требования к платформе и версии: JS (1.1), JVM (1.0), Native (1.3), Wasm-JS (1.8), Wasm-WASI (1.8)

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

Возвращает массив, если он не null, иначе — пустой массив.

Примеры

import kotlin.test.*

fun main() { 
   //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
}

© 2010–2026 JetBrains s.r.o. and Kotlin Programming Language contributors
Licensed under the Apache License, Version 2.0.
https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.collections/or-empty.html

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API