filterIsInstance所在位置是kotlin.sequences.filterIsInstance,其相关用法介绍如下。

用法一

fun <reified R> Sequence<*>.filterIsInstance(): Sequence<R>

返回包含作为指定类型参数 R 实例的所有元素的序列。

操作是 intermediatestateless

例子:

import kotlin.test.*

fun main(args: Array<String>) {
//sampleStart
open class Animal(val name: String) {
    override fun toString(): String {
        return name
    }
}
class Dog(name: String): Animal(name)
class Cat(name: String): Animal(name)

val animals: List<Animal> = listOf(Cat("Scratchy"), Dog("Poochie"))
val cats = animals.filterIsInstance<Cat>()

println(cats) // [Scratchy]
//sampleEnd
}

输出:

[Scratchy]

用法二

fun <R> Sequence<*>.filterIsInstance(
    klass: Class<R>
): Sequence<R>

返回包含作为指定类实例的所有元素的序列。

操作是 intermediatestateless

例子:

import kotlin.test.*

fun main(args: Array<String>) {
//sampleStart
open class Animal(val name: String) {
    override fun toString(): String {
        return name
    }
}
class Dog(name: String): Animal(name)
class Cat(name: String): Animal(name)

val animals: List<Animal> = listOf(Cat("Scratchy"), Dog("Poochie"))
val cats = animals.filterIsInstance(Cat::class.java)

println(cats) // [Scratchy]
//sampleEnd
}

输出:

[Scratchy]