【发布时间】:2021-04-21 20:27:54
【问题描述】:
我有一个看起来像这样的特质:
trait Ingredient[T] {
def foo(t: T): Unit = {
// Some complex logic
}
}
以及我想要为其设置方法的类型:
class Cheese
class Pepperoni
class Oregano
如何制作另一个具有方法的特征:
def foo(t: Cheese)
def foo(t: Pepperoni)
def foo(t: Oregano)
不复制代码?以下将不起作用,因为它多次从同一特征非法继承:
trait Pizza extends Ingredient[Cheese] with Ingredient[Pepperoni] with Ingredient[Oregano] {}
【问题讨论】:
-
那行不通,您的
foo方法必须选择一个(并且只有一个)T才能使用。您可以使用类型类而不是继承。这样您就可以提供三个不同的版本:IngredientFoo[Pizza, Cheese]、IngredientFoo[Pizza, Pepperoni]和IngredientFoo[Pizza, Oregano]并调用def foo[X,T](food: X, ingredient:T)(implicit handler: IngredientFoo[X,T]) = handler.foo(food, ingredient) -
只有当你想让食物和配料都可以独立扩展时,你才会这样做。如果没有,只需直接编码到您拥有的已知类型:
def fooCheese等 -
您可能需要提供更多有关您在此处尝试执行的操作的背景信息。
-
最好解释一下您要建模的元问题,以便我们提出替代方案。
标签: scala generics inheritance diamond-problem