Set Basics in Kotlin
Introduction
Set Basics is a fundamental concept every Kotlin developer should understand. Collections let you store and transform groups of values. Kotlin separates read-only and mutable views so you can express intent clearly in your APIs.
Set stores unique elements without guaranteed order (for hash sets). In this tutorial you will learn the syntax, walk through a complete example program, study the sample output, and review best practices so you can apply the concept confidently in your own projects.
Definition
- Set stores unique elements without guaranteed order (for hash sets).
- setOf() creates an immutable set.
- Duplicate values are automatically ignored.
Syntax
val set = setOf(1, 2, 2, 3)Set Basics in Kotlin Example Program in Kotlin
fun main(args: Array<String>) {
val ids = setOf(10, 20, 20, 30)
println(ids)
println("Size: ${ids.size}")
}Sample Output
[10, 20, 30]
Size: 3When to use
Use collections when the number of items is dynamic or when you need map/set semantics instead of a plain list.
How it works
-
The program starts with a
mainfunction — the entry point that runs when you execute the file. -
val ids = setOf(10, 20, 20, 30)assigns or updates a value used later in the program. -
The
println(ids)statement writes a line to the console — this produces part of the sample output below. -
The
println("Size: ${ids.size}")statement writes a line to the console — this produces part of the sample output below. -
Set stores unique elements without guaranteed order (for hash sets).
-
Run the program in IntelliJ IDEA, Android Studio, or with the Kotlin command-line compiler (
kotlinc/kotlin). Compare your console output with the sample output shown below.
Best Practices
Common Mistakes
Key Points
- Set stores unique elements without guaranteed order (for hash sets).
- setOf() creates an immutable set.
- Duplicate values are automatically ignored.
- Test the example locally and verify the output matches the sample.
- Experiment by changing input values to see how behaviour changes.
Notes
- Semicolons at the end of statements are optional in Kotlin.