路径依赖类型和泛型

时间:2017-02-07 11:17:32

标签: scala

我正在查看Abstract Members的示例。我们有以下路径依赖类型的示例。

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

假设我们想以下列方式在课堂上吃饭

class D[T <: Animal] {
  def blah(t: T, p: T): String = {
    t.eat(t)
  }
}

我得到type mismatch; expected t.SuitableFood, actual: T。我看到我正在进入泛型和路径依赖类型的水域。我很感激任何帮助。

由于

1 个答案:

答案 0 :(得分:2)

  

我怎么说它的类型为SuitableFood?

def blah(t: T)(food: t.SuitableFood) = ...

请注意,它必须位于单独的参数列表中才能依赖t

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)