0
0
Kotlinprogramming~5 mins

Set creation (setOf, mutableSetOf) in Kotlin

Choose your learning style9 modes available
Introduction

Sets help you store unique items without duplicates. You use setOf for fixed sets and mutableSetOf when you want to change the set later.

When you want to keep a list of unique names without repeats.
When you need to check if an item is already added quickly.
When you want to add or remove items from a collection during the program.
When you want to avoid duplicates in a collection of numbers or strings.
Syntax
Kotlin
val fixedSet = setOf(item1, item2, item3)
val changeableSet = mutableSetOf(item1, item2, item3)

setOf creates a read-only set that cannot be changed after creation.

mutableSetOf creates a set you can add or remove items from.

Examples
This creates a fixed set of colors. You cannot add or remove colors later.
Kotlin
val colors = setOf("red", "green", "blue")
This creates a set of numbers you can change. Here, we add the number 4.
Kotlin
val numbers = mutableSetOf(1, 2, 3)
numbers.add(4)
This creates an empty fixed set of strings.
Kotlin
val emptySet = setOf<String>()
This creates an empty mutable set of integers and adds 10 to it.
Kotlin
val emptyMutableSet = mutableSetOf<Int>()
emptyMutableSet.add(10)
Sample Program

This program shows how setOf removes duplicates automatically and how mutableSetOf lets you add items but ignores duplicates.

Kotlin
fun main() {
    val fruits = setOf("apple", "banana", "apple", "orange")
    println("Fixed set: $fruits")

    val mutableFruits = mutableSetOf("apple", "banana")
    mutableFruits.add("orange")
    mutableFruits.add("banana") // duplicate, won't be added
    println("Mutable set after additions: $mutableFruits")
}
OutputSuccess
Important Notes

Sets do not keep the order of items like lists do.

Adding a duplicate item to a set does nothing; the set stays the same.

Use mutableSetOf when you need to change the set after creating it.

Summary

setOf creates a fixed set with unique items.

mutableSetOf creates a set you can add or remove items from.

Sets automatically ignore duplicate items.