3

我有以下类层次结构:

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方法定义——我只是不知道我应该在那里指定什么类型才能让这段代码工作?

4

1 回答 1

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的技术。

于 2012-12-26T10:49:35.943 回答