This article explores different ways to merge two sets in Kotlin. Assume that the elements of both sets are mutually exclusive; otherwise, duplicates would be silently discarded during the merge process.

1. Using plus operator

The standard solution to join two sets in Kotlin is with the + operator or the plus() function. To illustrate, consider the following example, which creates a new set that is a join of both sets.

Download Code

2. Using addAll() function

Alternatively, you can call the addAll() function provided by the Set Interface to add all the specified collection elements to the result set.

Download Code

3. Using setOf() function

Another plausible way is to pass the expanded collection returned by the Spread operator * to the mutableSetOf() or setOf() function.

Download Code

4. Using Double Brace Initialization

You can also use Double Brace Initialization, which internally creates an anonymous inner class with an instance initializer in it. This approach should be best avoided.

Download Code

That’s all about merging two sets in Kotlin.