0
0
KotlinHow-ToBeginner · 3 min read

How to Create Set in Kotlin: Syntax and Examples

In Kotlin, you create a set using the setOf() function for an immutable set or mutableSetOf() for a mutable set. These functions take elements as arguments and return a set collection that stores unique values without order.
📐

Syntax

Use setOf() to create an immutable set that cannot be changed after creation. Use mutableSetOf() to create a set you can add or remove elements from later.

Example syntax:

  • val mySet = setOf(1, 2, 3) creates an immutable set.
  • val myMutableSet = mutableSetOf("a", "b") creates a mutable set.
kotlin
val immutableSet = setOf(1, 2, 3)
val mutableSet = mutableSetOf("a", "b", "c")
💻

Example

This example shows how to create both immutable and mutable sets, print them, and add an element to the mutable set.

kotlin
fun main() {
    val numbers = setOf(10, 20, 30, 20) // duplicate 20 ignored
    println("Immutable set: $numbers")

    val fruits = mutableSetOf("apple", "banana")
    println("Mutable set before adding: $fruits")
    fruits.add("orange")
    println("Mutable set after adding: $fruits")
}
Output
Immutable set: [10, 20, 30] Mutable set before adding: [apple, banana] Mutable set after adding: [apple, banana, orange]
⚠️

Common Pitfalls

One common mistake is trying to modify an immutable set created with setOf(), which will cause a compile error. Another is expecting sets to maintain insertion order; sets do not guarantee order.

Also, duplicates are automatically removed in sets, so adding the same element twice has no effect.

kotlin
fun main() {
    val mySet = setOf(1, 2, 3)
    // mySet.add(4) // Error: Unresolved reference: add

    val myMutableSet = mutableSetOf(1, 2, 3)
    myMutableSet.add(2) // No change, 2 already exists
    println(myMutableSet) // Output: [1, 2, 3]
}
Output
[1, 2, 3]
📊

Quick Reference

FunctionDescription
setOf(vararg elements)Creates an immutable set with given elements
mutableSetOf(vararg elements)Creates a mutable set with given elements
add(element)Adds an element to a mutable set
remove(element)Removes an element from a mutable set
contains(element)Checks if an element is in the set

Key Takeaways

Use setOf() to create an immutable set that cannot be changed.
Use mutableSetOf() to create a set you can add or remove elements from.
Sets automatically remove duplicate elements and do not maintain order.
Trying to modify an immutable set causes a compile-time error.
Use add() and remove() only on mutable sets.