Kotlin Set filterIsInstanceTo()
Syntax & Examples
Set.filterIsInstanceTo() extension function
The filterIsInstanceTo() extension function in Kotlin filters elements in a set, appending all elements that are instances of the specified type or class to the given destination collection.
Syntax of Set.filterIsInstanceTo()
There are 2 variations for the syntax of Set.filterIsInstanceTo() extension function. They are:
fun <R, C : MutableCollection<in R>> Set<*>.filterIsInstanceTo(destination: C): C
This extension function appends all elements that are instances of specified type parameter R to the given destination.
Returns value of type C
.
fun <C : MutableCollection<in R>, R> Set<*>.filterIsInstanceTo(destination: C, klass: Class<R>): C
This extension function appends all elements that are instances of specified class to the given destination.
Returns value of type C
.
✐ Examples
1 Appending instances of String to a list
Using filterIsInstanceTo() to filter elements in a set that are instances of String and append them to a list.
For example,
- Create a set containing elements of different types.
- Create an empty list to hold the filtered elements.
- Use filterIsInstanceTo() to filter elements that are instances of String and append them to the list.
- Print the resulting list.
Kotlin Program
fun main(args: Array<String>) {
val mixedSet: Set<Any> = setOf(1, "two", 3.0, "four", 5)
val stringList = mutableListOf<String>()
mixedSet.filterIsInstanceTo(stringList)
println(stringList)
}
Output
["two", "four"]
2 Appending instances of Int to a set
Using filterIsInstanceTo() to filter elements in a set that are instances of Int and append them to another set.
For example,
- Create a set containing elements of different types.
- Create an empty set to hold the filtered elements.
- Use filterIsInstanceTo() to filter elements that are instances of Int and append them to the new set.
- Print the resulting set.
Kotlin Program
fun main(args: Array<String>) {
val mixedSet: Set<Any> = setOf(1, "two", 3.0, 4, 5)
val intSet = mutableSetOf<Int>()
mixedSet.filterIsInstanceTo(intSet)
println(intSet)
}
Output
[1, 4, 5]
3 Appending instances of Double to a list
Using filterIsInstanceTo() to filter elements in a set that are instances of Double and append them to a list.
For example,
- Create a set containing elements of different types.
- Create an empty list to hold the filtered elements.
- Use filterIsInstanceTo() to filter elements that are instances of Double and append them to the list.
- Print the resulting list.
Kotlin Program
fun main(args: Array<String>) {
val mixedSet: Set<Any> = setOf(1, "two", 3.0, 4, 5)
val doubleList = mutableListOf<Double>()
mixedSet.filterIsInstanceTo(doubleList)
println(doubleList)
}
Output
[3.0]
Summary
In this Kotlin tutorial, we learned about filterIsInstanceTo() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.