【问题标题】:Using parameterized branch of ADT in function在函数中使用 ADT 的参数化分支
【发布时间】:2020-06-18 23:06:10
【问题描述】:

代码如下:

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 &lt;: Tr 并使其编译成功。有没有办法做到这一点?

我很确定 shapeless 在这里会有所帮助。

【问题讨论】:

标签: scala shapeless algebraic-data-types


【解决方案1】:

你可以使用简单的重载。

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,但我认为在这种情况下这将是矫枉过正。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-23
    • 1970-01-01
    • 1970-01-01
    • 2023-02-21
    • 2017-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多