The toMutableSet() extension function in Kotlin returns a new MutableSet containing all distinct elements from the given collection.
The syntax of Set.toMutableSet() extension function is:
fun <T> Iterable<T>.toMutableSet(): MutableSet<T>
This toMutableSet() extension function of Set returns a new MutableSet containing all distinct elements from the given collection.
Set.toMutableSet() returns value of type MutableSet
.
Using toMutableSet() to convert a set of integers to a MutableSet.
For example,
fun main() {
val intSet = setOf(1, 2, 3, 4, 5)
val mutableSet = intSet.toMutableSet()
println(mutableSet)
}
[1, 2, 3, 4, 5]
Using toMutableSet() to convert a set of strings to a MutableSet.
For example,
fun main() {
val stringSet = setOf("one", "two", "three")
val mutableSet = stringSet.toMutableSet()
println(mutableSet)
}
[one, two, three]
Using toMutableSet() to convert a set of custom objects to a MutableSet.
For example,
data class Person(val name: String, val age: Int)
fun main() {
val peopleSet = setOf(Person("Alice", 30), Person("Bob", 25), Person("Charlie", 35))
val mutableSet = peopleSet.toMutableSet()
println(mutableSet)
}
[Person(name=Alice, age=30), Person(name=Bob, age=25), Person(name=Charlie, age=35)]
In this Kotlin tutorial, we learned about toMutableSet() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.