Scala 多类型模式匹配 [英] Scala multiple type pattern matching

查看:42
本文介绍了Scala 多类型模式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何使用多类型模式匹配.我有:

I'm wondering how can I use multiple type pattern matching. I have:

abstract class MyAbstract

case class MyFirst extends MyAbstract
case class MySecond extends MyAbstract
case class MyThird extends MyAbstract // shouldn't be matched and shouldn't call doSomething()

val x: MyAbstract = MyFirst

x match { 
 case a: MyFirst => doSomething()
 case b: MySecond => doSomething()
 case _ => doSomethingElse()
}

所以我想写一些类似的东西:

So I'd like to write something like:

x match {
 case a @ (MyFirst | MySecond) => doSomething()
 case _ => doSomethingElse()
}

我在一些教程中看到了类似的结构,但它给了我错误:

I saw similar construction in some tutorial, but it gives me error:

pattern type is incompatible with expected type;
[error]  found   : object MyFirst
[error]  required: MyAbstract

那么有没有办法在 on case 子句中定义几种不同的类型?我认为这会使代码更漂亮.好像我会有 5 个,我会写 5 次相同的代码(调用 doSomething()).

So is there a way to define few different types in on case clause? I think it would make code prettier. As if I will have 5 of them, I will write same code 5 times (calling doSomething()).

提前致谢!

推荐答案

您的案例类缺少括号.不推荐使用没有参数列表的案例类.

You are missing the parenthesis for your case classes. Case classes without parameter lists are deprecated.

试试这个:

abstract class MyAbstract
case class MyFirst() extends MyAbstract
case class MySecond() extends MyAbstract

val x: MyAbstract = MyFirst()


x match {
   case aOrB @ (MyFirst() | MySecond()) => doSomething(aOrB)
   case _ => doSomethingElse()
}

如果你的 case 类有太多的参数并且不想写长的 Foo(_,_,..) 模式,那么也许:

If you have too many params for your case classes and don't like having to write long Foo(_,_,..) patterns, then maybe:

x match {
   case aOrB @ (_:MyFirst | _:MySecond) => doSomething(aOrB)
   case _ => doSomethingElse()
}

或者只是:

x match {
   case _:MyFirst | _:MySecond => doSomething(x) // just use x instead of aOrB
   case _ => doSomethingElse(x)
}

但也许您只是想要单例 case 对象?

But perhaps you just wanted singleton case objects?

abstract class MyAbstract
case object MyFirst extends MyAbstract
case object MySecond extends MyAbstract

val x: MyAbstract = MyFirst

x match {
   case aOrB @ (MyFirst | MySecond) => doSomething()
   case _ => doSomethingElse()
}

这篇关于Scala 多类型模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆