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

ParameterOptional/RequiredDescription
defaultValuerequiredA 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,

  1. Create an array of integers.
  2. Use ifEmpty() to return the array itself if it's not empty.
  3. 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,

  1. Create an empty array of integers.
  2. Use ifEmpty() to return a default array if the original array is empty.
  3. 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,

  1. Create an empty array of strings.
  2. Use ifEmpty() to return a custom default array if the original array is empty.
  3. 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.