在scala中匹配多个案例类
我正在对某些案例类进行匹配,并希望以相同的方式处理其中两个案例。像这样的事情:
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"
}
}
但是当我这样做时,我收到错误:
(fragment of test.scala):10: error: illegal variable in pattern alternative
case B(sb) | C(sc) => "B"
我可以让它工作,我从 B 和 C 的定义中删除参数,但如何与参数匹配?
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"
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
看起来您并不关心 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:
If you must, must, must extract the parameter and treat them in the same code block, you could:
Though I feel it would be much cleaner to factor that out into a method:
如果案例类之间有一些共性,我可以看到几种方法来实现您所追求的目标。第一个是让案例类扩展一个声明通用性的特征,第二个是使用结构类型,这样就无需扩展案例类。
结构类型方法会生成有关擦除的警告,目前我不确定如何消除。
There are a couple of ways that I can see to achieve what you are after, if you have some commonality between case classes. The first is to have the case classes extend a trait which declares the commonality, the second is to use a structural type which removes the need to extend your case classes.
The structural type method generates a warning about erasure which, at present I'm not sure how to eliminate.
嗯,这确实没有意义,不是吗? B 和 C 是互斥的,因此 sb 或 sc 被绑定,但您不知道哪个,因此您需要进一步的选择逻辑来决定使用哪个(假设它们绑定到 Option[String],而不是一个字符串)。所以没有任何收获:
或者这个:
Well, it doesn't really make sense, does it? B and C are mutually exclusive, so either sb or sc get bound, but you don't know which, so you'd need further selection logic to decide which to use (given that they were bound to a Option[String], not a String). So there's nothing gained over this:
Or this: