在 Scala 中匹配多个案例类 [英] Match multiple cases classes in scala
问题描述
我正在对某些案例类进行匹配,并希望以相同的方式处理其中的两个案例.像这样:
I'm doing matching against some case classes and would like to handle two of the cases in the same way. Something like this:
abstract class Foo
case class A extends Foo
case class B(s:String) extends Foo
case class C(s:String) extends Foo
def matcher(l: Foo): String = {
l match {
case A() => "A"
case B(sb) | C(sc) => "B"
case _ => "default"
}
}
但是当我这样做时,我得到了错误:
But when I do this I get the error:
(fragment of test.scala):10: error: illegal variable in pattern alternative
case B(sb) | C(sc) => "B"
我可以让它工作,因为我从 B 和 C 的定义中删除了参数,但是我如何与参数匹配?
I can get it working of I remove the parameters from the definition of B and C but how can I match with the params?
推荐答案
看来你不关心 String 参数的值,想把 B 和 C 一视同仁,所以:
Looks like you don't care about the values of the String parameters, and want to treat B and C the same, so:
def matcher(l: Foo): String = {
l match {
case A() => "A"
case B(_) | C(_) => "B"
case _ => "default"
}
}
如果你必须,必须,必须提取参数并在同一个代码块中处理它们,你可以:
If you must, must, must extract the parameter and treat them in the same code block, you could:
def matcher(l: Foo): String = {
l match {
case A() => "A"
case bOrC @ (B(_) | C(_)) => {
val s = bOrC.asInstanceOf[{def s: String}].s // ugly, ugly
"B(" + s + ")"
}
case _ => "default"
}
}
虽然我觉得把它分解成一个方法会更清晰:
Though I feel it would be much cleaner to factor that out into a method:
def doB(s: String) = { "B(" + s + ")" }
def matcher(l: Foo): String = {
l match {
case A() => "A"
case B(s) => doB(s)
case C(s) => doB(s)
case _ => "default"
}
}
这篇关于在 Scala 中匹配多个案例类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!