What is the mutableSetOf() method in Kotlin?

The mutableSetOf() method in Kotlin is used to create a mutable set. A mutable set is a set that allows both read and write operations.

Syntax

The mutableSetOf() method can be declared as shown below:

fun <T> mutableSetOf(vararg elements: T): MutableSet<T>
  • elements: The elements to be added to the set.

Return value

The mutableSetOf() method returns a mutable set containing the specified elements.

Example

Consider the code snippet below, which demonstrates the use of the mutableSetOf() method.

fun main(args: Array<String>) {
val set1 = mutableSetOf("aa", "bb", "cc")
println("set1: " + set1)
}

Explanation

The mutableSetOf() method is used in line 3 to create a mutable set of the three elements declared as parameters.

Free Resources