[英]Path-dependent types and generics
I am looking at an example from Abstract Members . 我正在看抽象成员的一个例子。 We have the following example of path-dependent types.
我们有以下路径依赖类型的示例。
class Food
abstract class Animal {
type SuitableFood <: Food
def eat(food: SuitableFood): String
}
class DogFood extends Food
class Dog extends Animal {
type SuitableFood = DogFood
override def eat(food: DogFood): String = food.toString
}
val lassie = new Dog
lassie eat new lassie.SuitableFood
Say we want to work with eat in an class in the following manner 假设我们想以下列方式在课堂上吃饭
class D[T <: Animal] {
def blah(t: T, p: T): String = {
t.eat(t)
}
}
I get type mismatch; expected t.SuitableFood, actual: T
我的
type mismatch; expected t.SuitableFood, actual: T
type mismatch; expected t.SuitableFood, actual: T
. type mismatch; expected t.SuitableFood, actual: T
。 I see that I am entering the waters of generics and path-dependent types. 我看到我正在进入泛型和路径依赖类型的水域。 I'd appreciate any help.
我很感激任何帮助。
Thanks 谢谢
How do I say it's of type SuitableFood?
我怎么说它的类型为SuitableFood?
def blah(t: T)(food: t.SuitableFood) = ...
Note that it has to be in a separate parameter list to depend on t
. 请注意,它必须位于单独的参数列表中以依赖于
t
。
The reason def blah(t: T, food: T#SuitableFood)
doesn't work is because it would allow below code: def blah(t: T, food: T#SuitableFood)
不起作用的原因是因为它允许下面的代码:
val lassie: Animal = new Dog
val cat: Animal = new Cat
val catFood: Animal#SuitableFood = new cat.SuitableFood
blah(lassie, catFood)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.