This article explores different ways to initialize a set in Kotlin.

1. Using Copy Constructor

You can initialize a set with elements of another collection. The idea is to use a copy constructor that accepts another collection. Note that any duplicates in the list will be silently discarded.

Download Code

2. Using toSet() function

Alternatively, you can call the toSet() function that accumulates the input elements into an unmodifiable instance of Set.

Download Code

 
It can be called upon another collection or an array. Here’s an example using a list:

Download Code

 
If you need a mutable instance of a set, you can use the toMutableSet() function.

Download Code

3. Using setOf() function

Kotlin provides a convenient way to create instances of Set with small numbers of elements with setOf() function. The setOf() function creates an immutable instance of Set, while mutableSetOf() function creates a mutable instance of it.

Download Code

4. Using addAll() function

You can initialize a MutableSet later with all elements of a collection or an array using the addAll() function.

Download Code

5. Using Double Brace Initialization

Although not recommended, you can use Double Brace Initialization in Kotlin, which creates an anonymous inner class with just an instance initializer in it.

Download Code

That’s all about initializing a set in Kotlin.