Kotlin Set toCollection()
Syntax & Examples
Set.toCollection() extension function
The toCollection() extension function in Kotlin appends all elements to the given destination collection.
Syntax of Set.toCollection()
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.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
destination | required | The collection to which elements will be appended. |
Return Type
Set.toCollection() returns value of type C
.
✐ Examples
1 Appending elements of a set to a mutable list
Using toCollection() to append elements of a set to a mutable list.
For example,
- Create a set of integers.
- Create a mutable list of integers.
- Use toCollection() to append the elements of the set to the mutable list.
- Print the resulting list.
Kotlin Program
fun main() {
val numbers = setOf(1, 2, 3)
val destination = mutableListOf<Int>()
numbers.toCollection(destination)
println(destination)
}
Output
[1, 2, 3]
2 Appending elements of a set of strings to a mutable set
Using toCollection() to append elements of a set of strings to a mutable set.
For example,
- Create a set of strings.
- Create a mutable set of strings.
- Use toCollection() to append the elements of the set to the mutable set.
- Print the resulting set.
Kotlin Program
fun main() {
val strings = setOf("one", "two", "three")
val destination = mutableSetOf<String>()
strings.toCollection(destination)
println(destination)
}
Output
[one, two, three]
3 Appending elements of a set of custom objects to a mutable list
Using toCollection() to append elements of a set of custom objects to a mutable list.
For example,
- Create a data class.
- Create a set of custom objects.
- Create a mutable list of custom objects.
- Use toCollection() to append the elements of the set to the mutable list.
- Print the resulting list.
Kotlin Program
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)
}
Output
[Person(name=Alice, age=30), Person(name=Bob, age=25)]
Summary
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.