Introduction
Kotlin Set Interface is a collection of components and can be organized in any order. The Set interface does not allow for duplicate elements. This interface is immutable, and its methods enable the set's read-only capabilities.
In this article, we will learn about Kotlin Sets and the need to use them. But before jumping into this, we would strongly recommend learning about Kotlin Arrays. We will learn how Sets are different from Arrays.
Kotlin makes a distinction between read-only and mutable sets. Read-only sets are produced with setOf(), and mutable sets are created with mutableSetOf().
Let’s move forward to understand this better with examples and uses.
Kotlin Set Interface
Set Interface employs the setOf() function to generate a list of set interface objects containing a list of elements.
Code:
fun main() {
//implicit, non generic definition, non duplicate items
val nonDuplicateSet = setOf(3, 2, '3', 4.0F, 5L, 3.0,"string",false,"3")
//explicit, generic definition, duplicate items
val duplicateSet: Set<Any> = setOf(3, 2, '3', '3', 4.0F, 5L, 3.0,"string",false,"3", 3.0)
println("Printing nonDuplicateSet which have $nonDuplicateSet")
println("Printing duplicateSet which have $duplicateSet")
}
Output:
Printing nonDuplicateSet which have [3, 2, 3, 4.0, 5, 3.0, string, false, 3]
Printing duplicateSet which have [3, 2, 3, 4.0, 5, 3.0, string, false, 3]
In above example, we have created two sets, one containing unique items and the second containing duplicate items using setOf(). Here a read-only set will be made, which is immutable.
Immutable means that their value can't be changed once defined. To make a mutable set, we will use mutableSetOf(), discussed later.
We can provide any value to the set, and it will implicitly typecast it to Any. We have declared duplicateSet variable explicitly to Any type.
Here, it is good to note that the output is the same in both cases, and it doesn't store duplicate items.
Now, we will see the functions of Set Interface.
Functions of Set Interface
We have a variety of functions that set provides to us. We will discuss some of them in the below example.
Code:
fun main() {
val nonDuplicateSet = setOf(1,2,3,4,5,6,7,8,9,10)
println(nonDuplicateSet.contains(11))
println(nonDuplicateSet.containsAll(listOf(1,2,3)))
println(nonDuplicateSet.drop(5))
println(nonDuplicateSet.isEmpty())
println(nonDuplicateSet.isNotEmpty())
}
Output:
false
true
[6, 7, 8, 9, 10]
false
true
We have used contains(), which will return a boolean depending on the element passed as the argument. containsAll() also gives boolean value, but we supply a list. If you want to know more about lists, you can head over to this article.
drop(n) will return a list containing all elements except the first n elements in the given set.
Lastly, isEmpty() and isNotEmpty() returns boolean value depending on if the list is empty or not.





