The ifEmpty() extension function in Kotlin returns the array itself if it's not empty, or the result of calling the defaultValue function if the array is empty.
The syntax of Set.ifEmpty() extension function is:
fun <C, R> C.ifEmpty(defaultValue: () -> R): R where C : Array<*>, C : R
This ifEmpty() extension function of Set returns this array if it's not empty or the result of calling defaultValue function if the array is empty.
Parameter | Optional/Required | Description |
---|---|---|
defaultValue | required | A function that provides a default value to return if the array is empty. |
Set.ifEmpty() returns value of type R
.
Using ifEmpty() to return the array itself if it contains elements.
For example,
fun main() {
val numbers = arrayOf(1, 2, 3)
val result = numbers.ifEmpty { arrayOf(0) }
println(result.joinToString())
}
1, 2, 3
Using ifEmpty() to return a default array if the original array is empty.
For example,
fun main() {
val numbers = emptyArray<Int>()
val result = numbers.ifEmpty { arrayOf(0) }
println(result.joinToString())
}
0
Using ifEmpty() to return a custom default array if the original array is empty.
For example,
fun main() {
val strings = emptyArray<String>()
val result = strings.ifEmpty { arrayOf("default") }
println(result.joinToString())
}
default
In this Kotlin tutorial, we learned about ifEmpty() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.