Kotlin setOf

πŸŽ“ Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.

▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube

▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube

In this guide, we will learn about the Kotlin setOf function with lot's of examples.

What is setOf()? 

The setOf() is a function in Kotlin’s standard library designed to create an immutable (read-only) set. A set is a collection that doesn't allow duplicate elements. Being immutable means that once a set is created using setOf(), its elements cannot be modified - you can't add or remove items. 

Basic Syntax:

val set: Set<Type> = setOf(element1, element2, element3, ...)

Examples with Outputs

Creating a Basic Set

val colors = setOf("Red", "Blue", "Green")
println(colors)  // Output: [Red, Blue, Green]

Uniqueness in Sets 

Sets inherently ensure the uniqueness of elements:

val numbers = setOf(1, 2, 3, 2, 1)
println(numbers)  // Output: [1, 2, 3]

Merging Two Sets 

Merging is simple and retains unique elements:

val set1 = setOf(1, 2, 3)
val set2 = setOf(3, 4, 5)
val mergedSet = set1 + set2
println(mergedSet)  // Output: [1, 2, 3, 4, 5]

Empty and Nullable Sets

val emptySet = setOf<String>()
println(emptySet)  // Output: []

val nullableSet = setOf(null, "Hello")
println(nullableSet)  // Output: [null, Hello]

Convert a Set to a List

val numSet = setOf(1, 2, 3)
val numList = numSet.toList()

Conclusion

Kotlin's setOf() provides a concise and idiomatic way to define immutable sets. In this guide, we went through the usage of the setOf() method with lots of examples.

Related Kotlin Posts

My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare