Kotlin Tutorials

Kotlin Set isEmpty()
Syntax & Examples

Set.isEmpty() function

The isEmpty() function of the Set class in Kotlin checks if the set is empty, returning true if it contains no elements and false otherwise.


Syntax of Set.isEmpty()

The syntax of Set.isEmpty() function is:

abstract fun isEmpty(): Boolean

This isEmpty() function of Set returns true if the collection is empty (contains no elements), false otherwise.

Return Type

Set.isEmpty() returns value of type Boolean.



✐ Examples

1 Using isEmpty() to check if a set is empty

In Kotlin, we can use the isEmpty() function to check if a set is empty.

For example,

  1. Create an empty set of integers.
  2. Use the isEmpty() function to check if the set is empty.
  3. Print the result to the console using the println function.

Kotlin Program

fun main(args: Array<String>) {
    val emptySet = emptySet<Int>()
    val isEmpty = emptySet.isEmpty()
    println("Is the set empty? $isEmpty")
}

Output

Is the set empty? true

2 Using isEmpty() with a non-empty set

In Kotlin, we can use the isEmpty() function to check if a non-empty set contains any elements.

For example,

  1. Create a set of strings.
  2. Use the isEmpty() function to check if the set is empty.
  3. Print the result to the console using the println function.

Kotlin Program

fun main(args: Array<String>) {
    val fruits = setOf("apple", "banana", "cherry")
    val isEmpty = fruits.isEmpty()
    println("Is the set empty? $isEmpty")
}

Output

Is the set empty? false

3 Using isEmpty() after adding elements to a mutable set

In Kotlin, the isEmpty() function can also be used with mutable sets to check if the set is empty after adding elements.

For example,

  1. Create a mutable set of strings.
  2. Add elements to the set.
  3. Use the isEmpty() function to check if the set is empty.
  4. Print the result to the console using the println function.

Kotlin Program

fun main(args: Array<String>) {
    val mutableSet = mutableSetOf<String>()
    mutableSet.add("apple")
    val isEmpty = mutableSet.isEmpty()
    println("Is the mutable set empty? $isEmpty")
}

Output

Is the mutable set empty? false

Summary

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