Kotlin List ifEmpty()
Syntax & Examples


Syntax of List.ifEmpty()

The syntax of List.ifEmpty() extension function is:

fun <C, R> C.ifEmpty( defaultValue: () -> R ): R where C : Array<*>, C : R

This ifEmpty() extension function of List returns this array if it's not empty or the result of calling defaultValue function if the array is empty.



✐ Examples

1 Example

In this example,

  • We create an empty array of strings named array1.
  • We define a defaultValue lambda function that returns a string "Default Value".
  • We use the ifEmpty() function on array1 with defaultValue.
  • Since array1 is empty, the result is the string "Default Value".
  • Finally, we print the result to standard output using println statement.

Kotlin Program

fun main(args: Array<String>) {
    val array1 = emptyArray<String>()
    val defaultValue = { "Default Value" }
    val result = array1.ifEmpty(defaultValue)
    println(result)
}

Output

Default Value

2 Example

In this example,

  • We create an array of integers named array2.
  • We define a defaultValue lambda function that returns another array of integers [5, 6, 7].
  • We use the ifEmpty() function on array2 with defaultValue.
  • Since array2 is not empty, the result is array2 itself.
  • Finally, we print the result after joining elements to a string and using println statement.

Kotlin Program

fun main(args: Array<String>) {
    val array2 = arrayOf(1, 2, 3, 4)
    val defaultValue = { arrayOf(5, 6, 7) }
    val result = array2.ifEmpty(defaultValue)
    println(result.joinToString())
}

Output

1, 2, 3, 4

3 Example

In this example,

  • We create an array of strings named array3.
  • We define a defaultValue lambda function that returns another array of strings ["orange"].
  • We use the ifEmpty() function on array3 with defaultValue.
  • Since array3 is not empty, the result is array3 itself.
  • Finally, we print the result after joining elements to a string and using println statement.

Kotlin Program

fun main(args: Array<String>) {
    val array3 = arrayOf("apple", "banana", "cherry")
    val defaultValue = { arrayOf("orange") }
    val result = array3.ifEmpty(defaultValue)
    println(result.joinToString())
}

Output

apple, banana, cherry

Summary

In this Kotlin tutorial, we learned about ifEmpty() extension function of List: the syntax and few working examples with output and detailed explanation for each example.