在函数中使用 ADT 的参数化分支

Using parameterized branch of ADT in function

代码如下:

sealed trait Tr
final case class A(a: String) extends Tr
final case class B(b: String) extends Tr

def markWithType[Type <: Tr](tr: Type): Type = tr match {
  //Compile error
  //Expression of type A doesn't conform to expected type Type
  case A(a) => A("A:" + a) 

  //Compile error
  //Expression of type B doesn't conform to expected type Type
  case B(b) => B("B:" + b)
}

问题是它无法编译。我想保留 Type <: Tr 并使其编译成功。有办法吗?

我很确定 shapeless 在这里很有用。

您可以使用简单的重载。

sealed trait Tr {
  def markWithType: Tr
}

final case class A(a: String) extends Tr {
  override def markWithType: A = A(s"A: ${a}")
}

final case class B(b: String) extends Tr {
  override def markWithType: B = B(s"B: ${b}")
}

另一种选择是 typeclass,但我认为在这种情况下这会有点矫枉过正。