这是代码:
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}")
}
另一个选择是类型类,但我相信在这种情况下这会有点过分。
关于scala - 在函数中使用 ADT 的参数化分支,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62453052/