Kotlin Set ifEmpty()
Syntax & Examples
Set.ifEmpty() extension function
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.
Syntax of Set.ifEmpty()
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.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
defaultValue | required | A function that provides a default value to return if the array is empty. |
Return Type
Set.ifEmpty() returns value of type R
.
✐ Examples
1 Returning the array itself if not empty
Using ifEmpty() to return the array itself if it contains elements.
For example,
- Create an array of integers.
- Use ifEmpty() to return the array itself if it's not empty.
- Print the resulting array.
Kotlin Program
fun main() {
val numbers = arrayOf(1, 2, 3)
val result = numbers.ifEmpty { arrayOf(0) }
println(result.joinToString())
}
Output
1, 2, 3
2 Returning a default array if empty
Using ifEmpty() to return a default array if the original array is empty.
For example,
- Create an empty array of integers.
- Use ifEmpty() to return a default array if the original array is empty.
- Print the resulting array.
Kotlin Program
fun main() {
val numbers = emptyArray<Int>()
val result = numbers.ifEmpty { arrayOf(0) }
println(result.joinToString())
}
Output
0
3 Returning a default array if empty with custom values
Using ifEmpty() to return a custom default array if the original array is empty.
For example,
- Create an empty array of strings.
- Use ifEmpty() to return a custom default array if the original array is empty.
- Print the resulting array.
Kotlin Program
fun main() {
val strings = emptyArray<String>()
val result = strings.ifEmpty { arrayOf("default") }
println(result.joinToString())
}
Output
default
Summary
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.