[英]Scala - a type-parametrized trait method returning a type-parametrized object - how to implement?
我有以下类层次结构:
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
方法定义中逃脱 - 我只是无法弄清楚我应该指定哪些类型的代码才能工作?
如果你覆盖这样的类型成员,它就有效。 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-有界多态的技术。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.