Kotlin Tutorials

Kotlin Set isNotEmpty()
Syntax & Examples

Set.isNotEmpty() extension function

The isNotEmpty() extension function in Kotlin returns true if the collection is not empty.


Syntax of Set.isNotEmpty()

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

fun <T> Collection<T>.isNotEmpty(): Boolean

This isNotEmpty() extension function of Set returns true if the collection is not empty.

Return Type

Set.isNotEmpty() returns value of type Boolean.



✐ Examples

1 Checking if a set of integers is not empty

Using isNotEmpty() to check if a set of integers is not empty.

For example,

  1. Create a set of integers.
  2. Use isNotEmpty() to check if the set is not empty.
  3. Print the result.

Kotlin Program

fun main() {
    val numbers = setOf(1, 2, 3)
    val result = numbers.isNotEmpty()
    println(result)
}

Output

true

2 Checking if an empty set of strings is not empty

Using isNotEmpty() to check if an empty set of strings is not empty.

For example,

  1. Create an empty set of strings.
  2. Use isNotEmpty() to check if the set is not empty.
  3. Print the result.

Kotlin Program

fun main() {
    val strings = emptySet<String>()
    val result = strings.isNotEmpty()
    println(result)
}

Output

false

3 Checking if a set of custom objects is not empty

Using isNotEmpty() to check if a set of custom objects is not empty.

For example,

  1. Create a data class.
  2. Create a set of custom objects.
  3. Use isNotEmpty() to check if the set is not empty.
  4. Print the result.

Kotlin Program

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

fun main() {
    val people = setOf(Person("Alice", 30), Person("Bob", 25))
    val result = people.isNotEmpty()
    println(result)
}

Output

true

Summary

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