class Apple : Fruit() //Apple继承Fruit
class Banana : Fruit() //Banana继承Fruit
class Grape : Fruit() //Grape继承Fruit
//两个函数
object GenericTypeDemo {
fun addFruit(fruit: MutableList){}
fun getFruit(fruit: MutableList<Fruit){}
}
这个时候可以这样调用上面的两个函数:
val fruits: MutableList = mutableListOf(Fruit(), Fruit(), Fruit())
GenericTypeDemo.addFruit(fruits)
GenericTypeDemo.getFruit(fruits)
现在又有一个存放Apple的List:
val aples: MutableList = mutableListOf(Apple(), Apple(), Apple())
由于Kotlin中的泛型和Java一样是非协变的。所以下面的调用是编译不通过的:
GenericTypeDemo.addFruit(apples)
GenericTypeDemo.getFruit(apples)
如果没有协变,我们不得不在GenericTypeDemp中在添加两行代码:
fun addApple(apple: MutableList)
fun getApple(apple: MutableList)
这样重复的代码是不可取的。
在Java中我们使用 <? extend T>
确定上界, 使用 <? super T><