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

Scala-返回类型参数化对象的类型参数化特征方法-如何实现?,scala,types,implementation,type-systems,traits,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

我有以下类层次结构:

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]
}

但是,类型系统不允许我在方法定义中忽略该
——我只是不知道应该在那里指定什么类型才能让代码工作?

如果您像这样重写类型成员,它就会工作。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)

trait Entity[E第二个变体削弱了从a
Seq[String]
映射到a
Seq[HasForm]
的能力,因为它无法推断类型参数……还有其他技巧吗?不确定你的意思。你能举个例子吗?你的意思是从a
Seq[Entity[a]
映射到a
Seq[Entity[B]]
?请忽略该评论,没有问题,这是我的错误。谢谢您的回答!
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)