Case 类 类型匹配

Case classes match on type

如果我尝试匹配变量的类型,如下面的代码所示:

object CaseClassesApp extends App {

  sealed trait A{}
  final case class B() extends A{} 
  final case class C() extends A{}

  def tryMatch(x: Any): String = x match {
    case B => "It's a B!"
    case C => "It's a C!"
    case _ => "nope"
  }

  var testB = new B()
  print(tryMatch(testB))
}

不应该给我"It's a B!"吗?为什么我收到的是 "nope"?

模式匹配应该是:

  def tryMatch(x: Any): String = x match {
    case B() => "It's a B!"
    case C() => "It's a C!"
    case _ => "nope"
  }

因为您想匹配 对象 而不是 类型

如果要匹配类型,可以使用TypeTag,如:

  import scala.reflect.runtime.universe._
  def tryMatch[T](x: T)(implicit t: TypeTag[T]): String = x match {
    case _ if t.tpe =:= typeOf[B] => "It's a B!"
    case _ if t.tpe =:= typeOf[C] => "It's a C!"
    case _ => "nope"
  }

如果你想输入匹配,你可以通过稍微修改你的代码来实现。

def tryMatch(x: Any): String = x match {
  case b:B => "It's a B!"
  case c:C => "It's a C!"
  case _ => "nope"
}

其他答案解释了如何修复它,但没有说明问题到底是什么。每个 case class 自动有一个同名的同伴 object,所以 case B 在匹配 Option 时就像 case None 一样工作:当 [=15] 匹配时=] 等于这个对象!如果您将 x: Any 替换为 x: A,编译器会告诉您匹配不可能起作用,因为对象 B 不是 A.[=20 的实例=]