zaxme zaxme - 1 year ago 82
Scala Question

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 = {

I get
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.


Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download