0
0
Kotlinprogramming~3 mins

Why Set creation (setOf, mutableSetOf) in Kotlin? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your program could instantly keep only unique items without you lifting a finger?

The Scenario

Imagine you have a list of items and you want to keep only unique ones, like a guest list where no name should appear twice. Doing this by checking each item manually is like crossing names off a paper list one by one.

The Problem

Manually checking for duplicates is slow and easy to mess up. You might forget to check some items or accidentally add duplicates, making your list messy and unreliable.

The Solution

Kotlin's setOf and mutableSetOf create collections that automatically keep only unique items. This means you don't have to worry about duplicates--they are handled for you, saving time and avoiding mistakes.

Before vs After
Before
val uniqueItems = mutableListOf<String>()
for (item in items) {
  if (!uniqueItems.contains(item)) {
    uniqueItems.add(item)
  }
}
After
val uniqueItems = setOf("apple", "banana", "apple")
What It Enables

You can easily manage collections of unique items without extra code, making your programs cleaner and more reliable.

Real Life Example

When building a contact app, you want to store phone numbers without duplicates. Using setOf ensures each number is saved only once, avoiding confusion and errors.

Key Takeaways

Manual duplicate checks are slow and error-prone.

setOf and mutableSetOf handle uniqueness automatically.

This makes your code simpler and your data cleaner.