Scala - 返回类型参数化对象的类型参数化特征方法 - 如何实现?

时间:2012-12-26 10:33:40

标签: scala types implementation type-systems traits

我有以下类层次结构:

trait Entity {
  type E <: Entity
  type S <: Something[E]
  def in: S
}

trait Something[E <: Entity] {
  def doSomething {
    // something
  }
}

class A extends Entity {
  def in = InA
  object InA extends Something[A]
}
class B extends Entity {
  def in = InB
  object InB extends Something[B]
}
class C extends Entity {
  def in = InC
  object InC extends Something[C]
}

以及我想要的其他地方:

val entities = Seq[Entity]
entities.map(_.in.doSomething)

但是,类型系统不允许我使用in方法定义 - 我只是无法弄清楚我应该指定哪些类型的代码才能工作?

1 个答案:

答案 0 :(得分:5)

如果你覆盖这样的类型成员,它就有效。 Scala不会自动推断它们。

class A extends Entity {
  type E = A
  type S = Something[A]
  def in = InA
  object InA extends Something[A]
}
class B extends Entity {
  type E = B
  type S = Something[B]
  def in = InB
  object InB extends Something[B]
}
class C extends Entity {
  type E = C
  type S = Something[C]
  def in = InC
  object InC extends Something[C]
}

另一个选择是取消类型成员并仅使用类型参数。

trait Entity[E <: Entity[E]] {
  def in: Something[E]
}

trait Something[E <: Entity[E]] {
  def doSomething {
    // something
  }
}

class A extends Entity[A] {
  def in = InA
  object InA extends Something[A]
}
class B extends Entity[B] {
  def in = InB
  object InB extends Something[B]
}
class C extends Entity[C] {
  def in = InC
  object InC extends Something[C]
}

val entities = Seq[Entity[_]]()
entities.map(_.in.doSomething)

这使用了一种名为F-bounded polymorphism的技术。