class demo_泛型 {
@Test
fun main(){
//泛型接口调用
val drinkApple = DrinkApple()
drinkApple.drink("ding")
//泛型类调用
val blueColor = BlueColor("blue")
blueColor.printColor()
//泛型方法调用 传入的class参数
fromjson<String>("{}",String::class.java)
//泛型约束调用
fromjson2<demo1>("{}",demo1::class.java)
//泛型约束调用2
fromjson3<User>("{}",User::class.java)
}
//1、泛型接口
interface Drinks<T>{
fun drink(t: T)
}
//实现接口
class DrinkApple :Drinks<String>{
override fun drink(t: String) {
println("drink:${t}")
}
}
//2、泛型类
abstract class Color<T>(val t:T/*泛型字段*/){
abstract fun printColor()
}
//实现类
class BlueColor(val color :String):Color<String>(color){
override fun printColor() {
println("printColor:${color}")
}
}
//3、泛型方法
fun <T>fromjson(json:String,tClass:Class<T>):T?/*?代表可空的*/{
val instance:T? = tClass.newInstance()
return instance
}
//3、泛型限定方法 必须是demo的类或子类才能调用
fun <T:demo1>fromjson2(json:String,tClass:Class<T>):T?/*?代表可空的*/{
val instance:T? = tClass.newInstance()
return instance
}
//4、泛型限定方法2 所传递的类型T必须同时满足 where 字句的所有条件
//在下面的示例中,类型 T 必须即实现类 demo1 也现实了 Comparable 接口
fun <T>fromjson3(json:String,tClass:Class<T>):T? where T:JSObject,T:Comparable<T>/*?代表可空的*/{
val instance:T? = tClass.newInstance()
return instance
}
class User:JSObject(),Comparable<User>{
override fun compareTo(other: User): Int {
return 0
}
override fun call(methodName: String?, vararg args: Any?): Any {
TODO("Not yet implemented")
}
override fun eval(s: String?): Any {
TODO("Not yet implemented")
}
override fun getMember(name: String?): Any {
TODO("Not yet implemented")
}
override fun setMember(name: String?, value: Any?) {
TODO("Not yet implemented")
}
override fun removeMember(name: String?) {
TODO("Not yet implemented")
}
override fun getSlot(index: Int): Any {
TODO("Not yet implemented")
}
override fun setSlot(index: Int, value: Any?) {
TODO("Not yet implemented")
}
}
}
Android Kotlin 从入门到精通(五、泛型)
最新推荐文章于 2024-04-15 09:20:47 发布