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
- 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
- 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
- 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.