Scala mapping multiple types of patterns

I am wondering how I can use multiple template templates. 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 would like to write something like:

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

I saw a similar construction in some kind of tutorial, but this gives me an error:

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

So is there a way to define several different types in the case section? I think this will make the code more beautiful. As if I will have 5 of them, I will write the same code 5 times (doSomething () call).

Thanks in advance!

+45
types scala pattern-matching
Mar 27 '13 at 9:47
source share
1 answer

You are missing parentheses for case classes. Classes without parameter lists are deprecated.

Try the following:

 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() } 

If you have too many parameters for your case classes and don’t like writing long Foo(_,_,..) patterns Foo(_,_,..) , then it’s possible:

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

Or simply:

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

But maybe you just need one-dimensional 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() } 
+87
Mar 27 '13 at 9:58
source share



All Articles