Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare and initialize a MutableSet in Kotlin?

Tags:

syntax

kotlin

How to declare a MutableSet<Int> with the values 1, 2 and 3?

like image 675
Paul Jurczak Avatar asked Nov 08 '15 14:11

Paul Jurczak


People also ask

How do you initialize mutable Set Kotlin?

To create an empty Set in Kotlin, call setOf() function with no values passed to it. setOf() function creates an immutable Set with the values provided, if any. To create an empty mutable set, call mutableSetOf() function with no values passed to it.


2 Answers

Kotlin doesn't have its own implementations of collection interfaces. You can use standard Java sets such as HashSet or TreeSet, or any other set implementation out there. HashSet is the most popular one, and the preferred way of creating a HashSet from given elements is using the hashSetOf function:

val set: MutableSet<Int> = hashSetOf(1, 2, 3)
like image 138
Alexander Udalov Avatar answered Oct 11 '22 09:10

Alexander Udalov


I would use mutableSetOf:

val s = mutableSetOf(1, 2, 3)

which is a kotlin.collections.LinkedHashSet under the hood.

like image 34
Willi Mentzel Avatar answered Oct 11 '22 09:10

Willi Mentzel