scala使用反射进行模式匹配的正确方法

时间:2013-11-13 13:28:33

标签: scala pattern-matching

尝试重构并改进此模式匹配:

abstract class SuperClass
case class Foo() extends SuperClass
case class Bar() extends SuperClass

def getTheClass(param:String)={
 Class.forName(param)
}

val bazz = getTheClass(classOf[Foo].getName)

bazz match{
  case b if b == classOf[Bar] => "I am Bar"
  case f if f == classOf[Foo] => "I am Foo"
}

没有卫兵是否有优雅的方式?

1 个答案:

答案 0 :(得分:1)

完全基于字符串进行匹配:

abstract class SuperClass
case class Foo() extends SuperClass
case class Bar() extends SuperClass

val FooClass = classOf[Foo].getName
val BarClass = classOf[Bar].getName

val bazz = classOf[Foo].getName

bazz match{
  case BarClass => "I am Bar"
  case FooClass => "I am Foo"
}