[英]Scala - a type-parametrized trait method returning a type-parametrized object - how to implement?
I have the following class hierarchy: 我有以下类层次结构:
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]
}
and somewhere else I want to: 以及我想要的其他地方:
val entities = Seq[Entity]
entities.map(_.in.doSomething)
however, the type system does not let me get away with that in
method definition - I just can't figure out what types should I specify there for the piece of code to work? 但是,类型系统不允许我
in
方法定义中逃脱 - 我只是无法弄清楚我应该指定哪些类型的代码才能工作?
It works if you override the type members like this. 如果你覆盖这样的类型成员,它就有效。 Scala does not infer them automatically.
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]
}
Another option would be to do away with type members and only use type parameters. 另一种选择是取消类型成员并仅使用类型参数。
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)
This uses a technique called F-bounded polymorphism . 这使用了一种称为F-有界多态的技术。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.