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.
Comments
Post a Comment
Leave Comment