Kotlin Tutorials

Kotlin Set orEmpty()
Syntax & Examples

Set.orEmpty() extension function

The orEmpty() extension function in Kotlin returns the original set if it is not null, and the empty set otherwise.


Syntax of Set.orEmpty()

The syntax of Set.orEmpty() extension function is:

fun <T> Set<T>?.orEmpty(): Set<T>

This orEmpty() extension function of Set returns this Set if it's not null and the empty set otherwise.

Return Type

Set.orEmpty() returns value of type Set.



✐ Examples

1 Returning the original set if it is not null

Using orEmpty() to return the original set if it is not null.

For example,

  1. Create a nullable set of integers.
  2. Use orEmpty() to return the original set if it is not null.
  3. Print the resulting set.

Kotlin Program

fun main() {
    val numbers: Set<Int>? = setOf(1, 2, 3)
    val result = numbers.orEmpty()
    println(result)
}

Output

[1, 2, 3]

2 Returning an empty set if the original set is null

Using orEmpty() to return an empty set if the original set is null.

For example,

  1. Create a nullable set of integers and set it to null.
  2. Use orEmpty() to return an empty set.
  3. Print the resulting set.

Kotlin Program

fun main() {
    val numbers: Set<Int>? = null
    val result = numbers.orEmpty()
    println(result)
}

Output

[]

3 Handling a nullable set of strings

Using orEmpty() to handle a nullable set of strings, returning the original set if it is not null, and an empty set otherwise.

For example,

  1. Create a nullable set of strings.
  2. Use orEmpty() to return the original set if it is not null.
  3. Print the resulting set.

Kotlin Program

fun main() {
    val strings: Set<String>? = setOf("one", "two", "three")
    val result = strings.orEmpty()
    println(result)
}

Output

[one, two, three]

Summary

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