The toCollection() extension function in Kotlin appends all elements to the given destination collection.
The syntax of Set.toCollection() extension function is:
fun <T, C : MutableCollection<in T>> Set<T>.toCollection(destination: C): C
This toCollection() extension function of Set appends all elements to the given destination collection.
Parameter | Optional/Required | Description |
---|---|---|
destination | required | The collection to which elements will be appended. |
Set.toCollection() returns value of type C
.
Using toCollection() to append elements of a set to a mutable list.
For example,
fun main() {
val numbers = setOf(1, 2, 3)
val destination = mutableListOf<Int>()
numbers.toCollection(destination)
println(destination)
}
[1, 2, 3]
Using toCollection() to append elements of a set of strings to a mutable set.
For example,
fun main() {
val strings = setOf("one", "two", "three")
val destination = mutableSetOf<String>()
strings.toCollection(destination)
println(destination)
}
[one, two, three]
Using toCollection() to append elements of a set of custom objects to a mutable list.
For example,
data class Person(val name: String, val age: Int)
fun main() {
val people = setOf(Person("Alice", 30), Person("Bob", 25))
val destination = mutableListOf<Person>()
people.toCollection(destination)
println(destination)
}
[Person(name=Alice, age=30), Person(name=Bob, age=25)]
In this Kotlin tutorial, we learned about toCollection() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.