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

我有以下类层次结构:

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)

但是,类型系统不允许我在方法定义中逃脱 – 我只是无法弄清楚我应该指定哪些类型的代码才能工作?

最佳答案
如果你覆盖这样的类型成员,它就有效. 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的技术.

转载注明原文:Scala – 返回类型参数化对象的类型参数化特征方法 – 如何实现? - 代码日志