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

Kotlin – Create a Set of Strings

To create a Set of Strings in Kotlin, call setOf() function, and pass the String elements to this function. setOf() returns an immutable Set created with the elements passed to it. To create an Mutable Set, use mutableSetOf() function.

In this tutorial, we will learn how to create a Set of Strings using setOf() and mutableSetOf() functions.

Examples

1. Create set of string elements

In the following example, we will use setOf() function and create a Set of Strings. We shall pass the elements: “abc”, “xyz”, “pqr”; to the setOf() function.

Main.kt

</>
Copy
fun main(args: Array<String>) {
    var mySet = setOf("abc", "xyz", "pqr")
    println("Set of Strings (Immutable) : ${mySet}")
}

Since, we are passing the String values to setOf() function, no explicit declaration of the variable as Set<String> or setOf<String>() is required. If we are creating an empty Set of Strings, then we must specify the type of elements we store in this Set.

Output

Set of Strings (Immutable) : [abc, xyz, pqr]

1. Create a mutable set of string elements

Now, let an create a Mutable Set of Strings using mutableSetOf() function.

Main.kt

</>
Copy
fun main(args: Array<String>) {
    var myMutableSet = mutableSetOf("abc", "xyz", "pqr")
    println("Set of Strings (Mutable) : ${myMutableSet}")
}

Output

Set of Strings (Mutable) : [abc, xyz, pqr]

Conclusion

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