使用任何类型的泛型参数化作为函数参数



我希望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>,其中TFruit的超类型(由于BoxOf的约束,也是Food的子类型)。

最新更新