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

标签 scala shapeless algebraic-data-types

这是代码:

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/

相关文章:

scala - 如何使用 Scala 的蛋糕模式来实现机器人腿?

scala - 如何使用sbt-proguard实现类似maven的依赖阴影?

scala - '结果的长度应为 3' : How does the ScalaTest DSL work?

scala - 使用 "Prolog in Scala"查找可用的类型类实例

haskell - 为什么在代数数据类型中,如果我可以为两种类型定义一个特殊的 `from` 和 `to` 函数,这两种类型就可以认为是相等的?

scala - 类型构造函数作为返回类型

scala - 为什么sbt-native-packager将bin/start登台为目录而不是脚本?

scala - 如何将大小写与无形变量匹配?

scala - 将列表转换为案例类

haskell - 在这个类型化的 lambda 演算宇宙中,您如何制定 n 元积和求和类型?