class MyList<T> {
fun get(pos: Int): T {
TODO("implement")
}
fun addItem(item: T) {}
}
默认 T 可为 null
相当于
class MyList<T:Any?> {
fun get(pos: Int): T {
TODO("implement")
}
fun addItem(item: T) {}
}
如果想不为null,则
class MyList<T:Any> {
fun get(pos: Int): T {
TODO("implement")
}
fun addItem(item: T) {}
}
check
如果waterSupply.needsProcessing为true,则抛出异常
class Aquarium<T: WaterSupply>(val waterSupply: T) {
fun addWater() {
check(!waterSupply.needsProcessing) { "water supply needs processing first" }
println("adding water from \$waterSupply")
}
}
泛型函数
fun <T: WaterSupply> isWaterClean(aquarium: Aquarium<T>) {
println("aquarium water is clean: ${!aquarium.waterSupply.needsProcessing}")
}
泛型方法
inline fun <reified R: WaterSupply> hasWaterSupplyOfType() = waterSupply is R
扩展函数
inline fun <reified R: WaterSupply> Aquarium<*>.hasWaterSupplyOfType() = waterSupply is R
inline fun <reified R: WaterSupply> Aquarium<*>.hasWaterSupplyOfType() = waterSupply is R
网友评论