if Empty
Returns this array if it's not empty or the result of calling defaultValue function if the array is empty.
Since Kotlin
1.3
Samples
import samples.*
import kotlin.test.*
fun main() {
//sampleStart
val emptyArray: Array<Any> = emptyArray()
val emptyOrNull: Array<Any>? = emptyArray.ifEmpty { null }
assertPrints(emptyOrNull, "null")
val emptyOrDefault: Array<Any> = emptyArray.ifEmpty { arrayOf("default") }
assertPrints(emptyOrDefault.contentToString(), "[default]")
val nonEmptyArray = arrayOf(1)
val sameArray = nonEmptyArray.ifEmpty { arrayOf(2) }
assertTrue(nonEmptyArray === sameArray)
//sampleEnd
}
Returns this collection if it's not empty or the result of calling defaultValue function if the collection is empty.
Since Kotlin
1.3
Samples
import samples.*
import kotlin.test.*
fun main() {
//sampleStart
val empty: List<Int> = emptyList()
val emptyOrNull: List<Int>? = empty.ifEmpty { null }
assertPrints(emptyOrNull, "null")
val emptyOrDefault: List<Any> = empty.ifEmpty { listOf("default") }
assertPrints(emptyOrDefault, "[default]")
val nonEmpty = listOf("x")
val sameList: List<String> = nonEmpty.ifEmpty { listOf("empty") }
assertTrue(nonEmpty === sameList)
//sampleEnd
}
Returns this map if it's not empty or the result of calling defaultValue function if the map is empty.
Since Kotlin
1.3
Samples
import samples.*
import kotlin.test.*
import java.util.*
fun main() {
//sampleStart
val emptyMap: Map<String, Int> = emptyMap()
val emptyOrNull = emptyMap.ifEmpty { null }
assertPrints(emptyOrNull, "null")
val emptyOrDefault: Map<String, Any> = emptyMap.ifEmpty { mapOf("s" to "a") }
assertPrints(emptyOrDefault, "{s=a}")
val nonEmptyMap = mapOf("x" to 1)
val sameMap = nonEmptyMap.ifEmpty { null }
assertTrue(nonEmptyMap === sameMap)
//sampleEnd
}