This article explores different ways to convert an array to a set using Kotlin. Assume that the array contains all distinct elements; otherwise, all duplicates would be silently discarded.

1. Using toSet() function

In Kotlin, the standard way to convert the specified array to a set is with the toSet() or toMutableSet() function.

Download Code

2. Using setOf() function

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

Download Code

3. Using for loop

Finally, you can write your own custom logic for this task. The idea is to create an empty set and push every element of the specified array to it using a for-loop.

Download Code

That’s all about converting an array to a set in Kotlin.