Initialize a set in Kotlin
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.
1 2 3 4 5 |
fun main() { val set: MutableSet<Int> = HashSet(listOf(1, 2, 3)) println(set) // [1, 2, 3] } |
2. Using toSet()
function
Alternatively, you can call the toSet()
function that accumulates the input elements into an unmodifiable instance of Set.
1 2 3 4 5 |
fun main() { val set: Set<Int> = (1..3).toSet() println(set) // [1, 2, 3] } |
It can be called upon another collection or an array. Here’s an example using a list:
1 2 3 4 5 |
fun main() { val set: Set<Int> = listOf(1, 2, 3).toSet() println(set) // [1, 2, 3] } |
If you need a mutable instance of a set, you can use the toMutableSet()
function.
1 2 3 4 5 |
fun main() { val set: MutableSet<Int> = arrayOf(1, 2, 3).toMutableSet() println(set) // [1, 2, 3] } |
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.
1 2 3 4 5 |
fun main() { val set: Set<Int> = setOf(1, 2, 3) println(set) // [1, 2, 3] } |
4. Using addAll()
function
You can initialize a MutableSet
later with all elements of a collection or an array using the addAll()
function.
1 2 3 4 5 6 |
fun main() { val set: MutableSet<Int> = HashSet() set.addAll(1..3) println(set) // [1, 2, 3] } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 |
fun main() { val set: HashSet<Int?> = object : HashSet<Int?>() { init { add(1) add(2) add(3) } } println(set) // [1, 2, 3] } |
That’s all about initializing a set in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)