Kotlin Tutorials

Kotlin Set isNullOrEmpty()
Syntax & Examples

Set.isNullOrEmpty() extension function

The isNullOrEmpty() extension function in Kotlin returns true if the nullable collection is either null or empty.


Syntax of Set.isNullOrEmpty()

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

fun <T> Collection<T>?.isNullOrEmpty(): Boolean

This isNullOrEmpty() extension function of Set returns true if this nullable collection is either null or empty.

Return Type

Set.isNullOrEmpty() returns value of type Boolean.



✐ Examples

1 Checking if a nullable set of integers is null or empty

Using isNullOrEmpty() to check if a nullable set of integers is either null or empty.

For example,

  1. Create a nullable set of integers that is not null and not empty.
  2. Use isNullOrEmpty() to check if the set is either null or empty.
  3. Print the result.

Kotlin Program

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

Output

false

2 Checking if a nullable set of strings is null or empty

Using isNullOrEmpty() to check if a nullable set of strings is either null or empty.

For example,

  1. Create a nullable set of strings that is null.
  2. Use isNullOrEmpty() to check if the set is either null or empty.
  3. Print the result.

Kotlin Program

fun main() {
    val strings: Set<String>? = null
    val result = strings.isNullOrEmpty()
    println(result)
}

Output

true

3 Checking if a nullable set of custom objects is null or empty

Using isNullOrEmpty() to check if a nullable set of custom objects is either null or empty.

For example,

  1. Create a data class.
  2. Create a nullable set of custom objects that is empty.
  3. Use isNullOrEmpty() to check if the set is either null or empty.
  4. Print the result.

Kotlin Program

data class Person(val name: String, val age: Int)

fun main() {
    val people: Set<Person>? = emptySet()
    val result = people.isNullOrEmpty()
    println(result)
}

Output

true

Summary

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