Skip to content

Kotlin 泛型

约 163 字小于 1 分钟

Androidkotlin

2023-08-13

协变and逆变

java

List<? extends TextView> textViews // 协变
List<? super Button> textViews // 逆变

kotlin

var textViews: List<out TextView> // 协变
var textViews: List<in TextView> // 逆变

where 关键字

Java

class Monster<T extends Animal & Food>{ 
}

kotlin

class Monster<T> where T : Animal, T : Food

reified 关键字

由于 Java 中的泛型存在类型擦除的情况,任何在运行时需要知道泛型确切类型信息的操作都没法用了。

检查一个对象是否为泛型类型 T 的实例(Java不可以这样写)

 👇         👇
inline fun <reified T> printIfTypeMatch(item: Any) {
    if (item is T) { // 👈
        println(item)
    }
}