Kotlin Array.filterIsInstance()

Kotlin Array.filterIsInstance() function

In Kotlin, the Array.filterIsInstance() function is used to filter elements of an array based on their runtime type. It returns a new array containing only the elements that are instances of the specified class or its subclasses.

This function is useful when you want to extract elements of a specific type from an array containing elements of various types.

In this tutorial, we’ll explore the syntax of the Array.filterIsInstance() function and provide examples of its usage in Kotlin arrays.

Syntax

The syntax of the Array.filterIsInstance() function is as follows:

inline fun <reified R> Array<*>.filterIsInstance(): List<R>

where

ParameterDescription
RThe class or interface to filter elements by.
Parameter of Array filterIsInstance() function

The Array.filterIsInstance() function returns a list of the filtered elements.

Examples for Array.filterIsInstance() function

1. Filtering Integers from an Array of Mixed Types

In this example, we’ll use filterIsInstance() function to filter only Int type values from the given array mixedArray that contains elements of various types.

Kotlin Program

fun main() {
    val mixedArray = arrayOf("apple", 123, 45.67, 89, "banana", 12.34, "kiwi", 56)

    // Filtering integers from the mixed array
    val integersList = mixedArray.filterIsInstance<Int>()

    // Printing the original mixed array and the result list
    println("Given Array\n${mixedArray.joinToString(", ")}\n")
    println("Filtered Integers\n${integersList.joinToString(", ")}")
}

Output

Given Array
apple, 123, 45.67, 89, banana, 12.34, kiwi, 56

Filtered Integers
123, 89, 56

2. Filtering Strings from an Array of Mixed Types

In this example, we’ll use filterIsInstance() function to filter only String type values from the given array mixedArray that contains elements of various types.

Kotlin Program

fun main() {
    val mixedArray = arrayOf("apple", 123, 45.67, 89, "banana", 12.34, "kiwi", 56)

    // Filtering strings from the mixed array
    val stringsList = mixedArray.filterIsInstance<String>()

    // Printing the original mixed array and the result list
    println("Given Array\n${mixedArray.joinToString(", ")}\n")
    println("Filtered Strings\n${stringsList.joinToString(", ")}")
}

Output

Given Array
apple, 123, 45.67, 89, banana, 12.34, kiwi, 56

Filtered Strings
apple, banana, kiwi

Summary

In this tutorial, we’ve covered the filterIsInstance() function in Kotlin arrays, its syntax, and how to use it to filter elements based on their runtime type. This function is particularly useful when dealing with arrays containing elements of diverse types.