What is the Set : setOf() method in Kotlin?

The setOf() method in Kotlin is used to create an immutable set. An immutable set is read-only and its elements cannot be modified.

Syntax

The setOf() method can be declared as shown in the code snippet below:

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

Return value

The setOf() method returns an immutable set containing the specified elements.

Example

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

fun main(args: Array<String>) {
val set1 = setOf("a", "b", "c")
println("set1: " + set1)
val set2 = setOf(1, 2, 3)
println("set2: " + set2)
}

Explanation

  • Line 3-4: The setOf() method is used in line 3 to create an immutable set of the three characters declared as parameters. The three characters declared as parameters are the elements of the set set1.

  • Line 6-7: The setOf() method is used in line 6 to create an immutable set of the three integers declared as parameters. The three integers declared as parameters are the elements of the set set2.

Free Resources