我希望mutate
函数同时接受BoxOf<Food>
和BoxOf<Fruit>
。
interface Food
abstract class BoxOf<C : Food> {
val children: MutableList<C> = mutableListOf()
}
interface Fruit : Food
class Apple : Fruit
class Lemon : Fruit
class BoxOfFood : BoxOf<Food>()
class BoxOfFruit : BoxOf<Fruit>()
fun mutate(parent: BoxOf<Food>) {
parent.children.add(Apple())
parent.children.remove(Lemon())
}
fun test() {
mutate(BoxOfFood())
mutate(BoxOfFruit()) // Type mismatch: inferred type is BoxOfFruit but BoxOf<Food> was expected
}
Thanks in advance
既然你想给mutate
不同种类的BoxOf<T>
,并把各种各样的水果放在里面,它应该接受任何"消费"。Fruit
,即BoxOf<in Fruit>
:
fun mutate(parent: BoxOf<in Fruit>)
这允许您传递任何BoxOf<T>
,其中T
是Fruit
的超类型(由于BoxOf
的约束,也是Food
的子类型)。