Using Set

We'll cover the following

Creating sets in Kotlin

Sets are unordered collections of elements. Like the methods for creating List<T>, which has both immutable/read-only and mutable/read-write versions, you may create instances of Set<T> using setOf() or instances of MutableSet<T> using mutableSetOf(). You may also use hashSetOf() to get a reference of type java.util.HashSet<T>: linkedSetOf() for LinkedHashSet, and sortedSetOf() for TreeSet<T>.

Here’s a set of fruits, with a duplicate element:

// sets.kts
val fruits: Set<String> = setOf("Apple", "Banana", "Apple")

Since sets guarantee uniqueness of elements, the duplicate is discarded in the set created:

Get hands-on with 1400+ tech skills courses.