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

huangapple go评论58阅读模式
英文:

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&lt;Food&gt; and BoxOf&lt;Fruit&gt;.

interface Food

abstract class BoxOf&lt;C : Food&gt; {
    val children: MutableList&lt;C&gt; = mutableListOf()
}

interface Fruit : Food
class Apple : Fruit
class Lemon : Fruit

class BoxOfFood : BoxOf&lt;Food&gt;()
class BoxOfFruit : BoxOf&lt;Fruit&gt;()

fun mutate(parent: BoxOf&lt;Food&gt;) {
    parent.children.add(Apple())
    parent.children.remove(Lemon())
}

fun test() {
    mutate(BoxOfFood())
    mutate(BoxOfFruit()) // Type mismatch: inferred type is BoxOfFruit but BoxOf&lt;Food&gt; was expected
}

Thanks in advance

答案1

得分: 3

以下是翻译好的部分:

由于您想要为 mutate 提供不同种类的 BoxOf&lt;T&gt; 并将各种水果放入其中,它应该接受任何 Fruit 的“消费者”,这写作 BoxOf&lt;in Fruit&gt;

fun mutate(parent: BoxOf&lt;in Fruit&gt;)

这允许您传递任何 TFruit 的超类型(也是 Food 的子类型,由于 BoxOf 的约束)的 BoxOf&lt;T&gt;

英文:

Since you want to give mutate different kinds of BoxOf&lt;T&gt;, and put all kinds of fruits in it, it should take any "consumer" of Fruit, which is written BoxOf&lt;in Fruit&gt;:

fun mutate(parent: BoxOf&lt;in Fruit&gt;)

This allows you to pass any BoxOf&lt;T&gt; where T is a supertype of Fruit (and also a subtype of Food, due to the constraint of BoxOf).

huangapple
  • 本文由 发表于 2023年4月6日 19:06:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/75948805.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定