In this tutorial, you shall learn how to create a Set of Integers in Kotlin using setOf() or mutableSetOf() functions, with examples.

Kotlin – Create a Set of Integers

To create a Set of Integers in Kotlin, call setOf() function, and pass the integer elements to this function. setOf() returns an immutable Set created with the elements passed to it. To create an Mutable Set, use mutableSetOf() function.

In this tutorial, we will learn how to create a Set of Integers using setOf() and mutableSetOf() functions.

Examples

ADVERTISEMENT

1. Create a set of integer elements

In the following example, we will use setOf() function and create a Set of Integers. We shall pass the elements: 1, 4, 9, 16 to the setOf() function.

Main.kt

fun main(args: Array<String>) {
    var mySet = setOf(1, 4, 9, 16)
    println("Set of Integers (Immutable) : ${mySet}")
}

Since, we are passing the Integer values to setOf() function, no explicit declaration of the variable as Set<Int> or setOf<Int>() is required. If we are creating an empty Set of Int values, then we must specify the type of elements we store in this Set.

Output

Set of Integers (Immutable) : [1, 4, 9, 16]

2. Create a mutable set of integer elements

Now, let an create a Mutable Set of Integers using mutableSetOf() function.

Main.kt

fun main(args: Array<String>) {
    var myMutableSet = mutableSetOf(1, 4, 9, 16)
    println("Set of Integers (Mutable) : ${myMutableSet}")
}

Output

Set of Integers (Mutable) : [1, 4, 9, 16]

Conclusion

In this Kotlin Tutorial, we learned how to create a Set of Integers in Kotlin, using setOf() or mutableSetOf() functions, with the help of examples.