The orEmpty() extension function in Kotlin returns the original set if it is not null, and the empty set otherwise.
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.
Set.orEmpty() returns value of type Set
.
Using orEmpty() to return the original set if it is not null.
For example,
fun main() {
val numbers: Set<Int>? = setOf(1, 2, 3)
val result = numbers.orEmpty()
println(result)
}
[1, 2, 3]
Using orEmpty() to return an empty set if the original set is null.
For example,
fun main() {
val numbers: Set<Int>? = null
val result = numbers.orEmpty()
println(result)
}
[]
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,
fun main() {
val strings: Set<String>? = setOf("one", "two", "three")
val result = strings.orEmpty()
println(result)
}
[one, two, three]
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.