Kotlin Array.filterIsInstanceTo() function
In Kotlin, the Array.filterIsInstanceTo()
function is used to filter elements of an array based on their runtime type and add the filtered elements to the destination collection.
This function is similar to Array.filterIsInstance(), but it allows you to specify a destination collection to which the filtered elements will be added.
This function is useful when you want to extract elements of a specific type from an array containing elements of various types and collect the results in a specific collection.
In this tutorial, we’ll explore the syntax of the Array.filterIsInstanceTo()
function and provide examples of its usage in Kotlin arrays.
Syntax
The syntax of the Array.filterIsInstanceTo()
function is as follows:
inline fun <reified R, C : MutableCollection<in R>> Array<*>.filterIsInstanceTo(destination: C): C
where
Parameter | Description |
---|---|
R | The class or interface to filter elements by. |
C | The destination collection to which the filtered elements will be added. |
The Array.filterIsInstanceTo()
function returns the filtered elements in a List.
Examples for Array.filterIsInstanceTo() function
1. Filtering Integers to a MutableList
In this example, we’ll use filterIsInstanceTo()
to filter only integers from an array that contains elements of various types and add them to a MutableList
.
Kotlin Program
fun main() {
val mixedArray = arrayOf("apple", 123, 45.67, 89, "banana", 12.34, "kiwi", 56)
val integersList = mutableListOf<Int>()
// Filtering integers to a MutableList
mixedArray.filterIsInstanceTo(integersList)
// Printing the original mixed array and the result list
println("Mixed Array\n${mixedArray.joinToString(", ")}\n")
println("Integers Elements\n${integersList.joinToString(", ")}")
}
Output
Mixed Array
apple, 123, 45.67, 89, banana, 12.34, kiwi, 56
Integers Elements
123, 89, 56
2. Filtering Strings to a MutableSet
In this example, we’ll use filterIsInstanceTo()
to filter only strings from give array mixedArray
that contains elements of various types and add them to a MutableSet
.
Kotlin Program
fun main() {
val mixedArray = arrayOf("apple", 123, 45.67, 89, "banana", 12.34, "kiwi", 56)
val stringsList = mutableListOf<String>()
// Filtering strings to a MutableList
mixedArray.filterIsInstanceTo(stringsList)
// Printing the original mixed array and the result list
println("Mixed Array\n${mixedArray.joinToString(", ")}\n")
println("String Elements\n${stringsList.joinToString(", ")}")
}
Output
Mixed Array
apple, 123, 45.67, 89, banana, 12.34, kiwi, 56
String Elements
apple, banana, kiwi
Summary
In this tutorial, we’ve covered the Array.filterIsInstanceTo()
function in Kotlin arrays, its syntax, and how to use it to filter elements based on their runtime type while adding the results to a specified collection.