英文:
Use generic parameterized with any type as function parameter
问题
I want the mutate
function accepts both BoxOf<Food>
and 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.
英文:
I want the mutate
function accepts both BoxOf<Food>
and 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
答案1
得分: 3
以下是翻译好的部分:
由于您想要为 mutate
提供不同种类的 BoxOf<T>
并将各种水果放入其中,它应该接受任何 Fruit
的“消费者”,这写作 BoxOf<in Fruit>
:
fun mutate(parent: BoxOf<in Fruit>)
这允许您传递任何 T
是 Fruit
的超类型(也是 Food
的子类型,由于 BoxOf
的约束)的 BoxOf<T>
。
英文:
Since you want to give mutate
different kinds of BoxOf<T>
, and put all kinds of fruits in it, it should take any "consumer" of Fruit
, which is written BoxOf<in Fruit>
:
fun mutate(parent: BoxOf<in Fruit>)
This allows you to pass any BoxOf<T>
where T
is a supertype of Fruit
(and also a subtype of Food
, due to the constraint of BoxOf
).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论