1

尝试重构和改进这种模式匹配:

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"
}

没有守卫有优雅的方式吗?

4

1 回答 1

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"
}
于 2013-11-13T13:44:16.633 回答