Scala 扩展特征,方法返回各种类型,类型不匹配

scala extending trait with methods returing various types, types mismatch

我是这样做的:

sealed trait Foo[T] {
  def getA: Decoder[T]
  def getB: Either[Type1, Type2]
}

trait Hello[T] extends Foo[T] {
  def getA: Decoder[T]
  def getB: Type1
}

trait World[T] extends Foo[T] {
  def getA: Decoder[T]
  def getB: Type2
}

目前,Either 是定义所有类型的错误方法。如何解决?

您可以尝试缩小 return 儿童特征的类型

trait Hello[T] extends Foo[T] {
  def getA: Decoder[T]
  def getB: Left[Type1, Type2]
}

trait World[T] extends Foo[T] {
  def getA: Decoder[T]
  def getB: Right[Type1, Type2]
}

或者你可以尝试引入类型成员

sealed trait Foo[T] {
  def getA: Decoder[T]
  type Out
  def getB: Out
}

trait Hello[T] extends Foo[T] {
  def getA: Decoder[T]
  type Out = Type1
  def getB: Type1
}

trait World[T] extends Foo[T] {
  def getA: Decoder[T]
  type Out = Type2
  def getB: Type2
}

或者您可以尝试输入 class

sealed trait Foo[T] {
  type This <: Foo[T]
  def getA: Decoder[T]
  def getB(implicit tc: TC[T, This]): tc.Out
}

trait Hello[T] extends Foo[T] {
  type This <: Hello[T]
  def getA: Decoder[T]
}

trait World[T] extends Foo[T] {
  type This <: World[T]
  def getA: Decoder[T]
}

trait TC[T, F <: Foo[T]] {
  type Out
}
object TC {
  implicit def hello[T, F <: Hello[T]]: TC[T, F] { type Out = Type1 } = null
  implicit def world[T, F <: World[T]]: TC[T, F] { type Out = Type2 } = null
}