inline fun <C, R> C.ifEmpty( defaultValue: () -> R ): R where C : Array<*>, C : R
Returns this array if it's not empty or the result of calling defaultValue function if the array is empty.
import kotlin.test.*
fun main(args: Array<String>) {
//sampleStart
val emptyArray: Array<Any> = emptyArray()
val emptyOrNull: Array<Any>? = emptyArray.ifEmpty { null }
println(emptyOrNull) // null
val emptyOrDefault: Array<Any> = emptyArray.ifEmpty { arrayOf("default") }
println(emptyOrDefault.contentToString()) // [default]
val nonEmptyArray = arrayOf(1)
val sameArray = nonEmptyArray.ifEmpty { arrayOf(2) }
println("nonEmptyArray === sameArray is ${nonEmptyArray === sameArray}") // true
//sampleEnd
}
inline fun <M, R> M.ifEmpty( defaultValue: () -> R ): R where M : Map<*, *>, M : R
Returns this map if it's not empty or the result of calling defaultValue function if the map is empty.
import kotlin.test.*
import java.util.*
fun main(args: Array<String>) {
//sampleStart
val emptyMap: Map<String, Int> = emptyMap()
val emptyOrNull = emptyMap.ifEmpty { null }
println(emptyOrNull) // null
val emptyOrDefault: Map<String, Any> = emptyMap.ifEmpty { mapOf("s" to "a") }
println(emptyOrDefault) // {s=a}
val nonEmptyMap = mapOf("x" to 1)
val sameMap = nonEmptyMap.ifEmpty { null }
println("nonEmptyMap === sameMap is ${nonEmptyMap === sameMap}") // true
//sampleEnd
}
© 2010–2019 JetBrains s.r.o.
Licensed under the Apache License, Version 2.0.
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/if-empty.html