Home

filterIsInstance

FilterIsInstance is a Kotlin standard library function that filters elements of a collection by their runtime type and returns them cast to that type. It is defined as an inline function with a reified type parameter, which allows type checks to run at runtime without passing a separate Class object.

For Iterable collections, the signature is roughly: filterIsInstance<T>(): List<T>. For Sequences, there is a corresponding inline

Usage examples:

- val mixed = listOf(1, "two", 3.0, "four")

val strings = mixed.filterIsInstance<String>() // ["two", "four"]

- val items = sequenceOf(1, "a", 2.5, "b")

val numbers = items.filterIsInstance<Number>() // yields 1 and 2.5 when iterated

Semantics and behavior:

- Returns a collection containing only elements that are instances of T, cast to T.

- On Iterable, the result is a new List<T>. On Sequence, the result is a Sequence<T> and can

- Useful when a heterogeneous collection must be narrowed to elements of a specific type without explicit

Notes:

- Requires a reified type parameter, so it must be called in an inline function context or

- Works with reference types; primitive types are boxed as needed since Kotlin uses runtime type checks.

function
returning
a
Sequence<T>,
enabling
lazy
evaluation.
The
function
uses
the
reified
type
parameter
T
to
test
each
element
with
a
type
check
(element
is
T)
and
casts
matching
elements
to
T.
be
processed
lazily.
casting
or
manual
checks.
at
top
level
where
reified
generics
are
supported.