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
. 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?
def blah(t: T)(food: t.SuitableFood) = ...
Note that it has to be in a separate parameter list to depend on t
.
The reason def blah(t: T, food: T#SuitableFood)
doesn't work is because it would allow below code:
val lassie: Animal = new Dog
val cat: Animal = new Cat
val catFood: Animal#SuitableFood = new cat.SuitableFood
blah(lassie, catFood)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.