In this tutorial, you shall learn how to create an empty Set in Kotlin using setOf() or mutableSetOf() functions, with examples.

Kotlin – Empty Set

To create an empty Set in Kotlin, call setOf() function with no values passed to it. setOf() function creates an immutable Set with the values provided, if any.

To create an empty mutable set, call mutableSetOf() function with no values passed to it. mutableSetOf() function creates a Mutable Set with the values provided, if any.

In this tutorial, we will learn how to use setOf() or mutableSetOf() functions to create an empty set that is read-only or writable Sets respectively.

Examples

ADVERTISEMENT

1. Create an Empty Set using setOf()

In the following example, we will use setOf() function to create an empty Set. setOf() returns read-only Set, which means no modifications can be done further on this Set.

Main.kt

fun main(args: Array<String>) {
    var mySet: Set<Int> = setOf()
    println("Empty Set (Immutable) : ${mySet}")
}

Output

Empty Set (Immutable) : []

2. Create an Empty Set using mutableSetOf()

In the following example, we will use mutableSetOf() function to create an empty Mutable Set. mutableSetOf() returns mutable Set, which means modifications/update can be done further on this Set.

Main.kt

fun main(args: Array<String>) {
    var myMutableSet = mutableSetOf<Int>()
    println("Empty Set (Mutable) : ${myMutableSet}")
}

Output

Empty Set (Mutable) : []

Conclusion

In this Kotlin Tutorial, we learned how to create an Empty Set in Kotlin, using setOf() or mutableSetOf() functions, with the help of examples.