首页 文章

模式匹配在scala中的通用抽象类型

提问于
浏览
2

我有一个自递归类型:

trait Problem[P <: Problem[P]] {
  type Solution
}

现在,我想在 P#Solution 上进行模式匹配 . 设's assume we'在 case class Foo[P <: Problem[P]]() 内:

case ExampleCaseClass(s: P#Solution) if conditionApplies() =>
  // do sth

case ExampleCaseClass(s: P#Solution) =>
  // now sth else

当然它因类型擦除而失败 . 有没有办法让代码在scala中编译?

我见过类/类型标签,但我不确定它们是否可以在这种情况下使用 .

1 回答

  • 2

    您确实可以使用类型标记,但是您需要具体类型来从中获取类型标记 . 您可以将解决方案类型添加为类型参数:

    case class Foo[P <: Problem[P], S <: P#Solution:TypeTag]() {
      def doSomething[T:TypeTag](c: ExampleCaseClass[T]) = c match {
        case ExampleCaseClass(s) if typeOf[T] =:= typeOf[S] => "x"
        case ExampleCaseClass(s) => "y"
      }
    }
    

    如果要匹配子类型,请使用 <:< 而不是 =:= .

相关问题