Does scala have a test-if-match statement?

Possible duplicate:
Scala: a short form of pattern matching that returns a boolean

In my scala code, I often find myself writing the following:

x match{ case Type(params) => doStuffWith(params) case _ => /* do nothing*/ } 

Is there any predefined operator for this? I think it would be much clearer if I could write things like:

 if( x match Type(params)) { doStuffWith(params) } 

basically avoiding an accident. I also had other situations where the ability to check that something matches the pattern in the built-in way will save me from an extra pair of curly braces.

I know that such a thing can only be useful when writing more iterative code, but scala seems to have so many hidden functions that I was wondering if anyone has a simple solution for this.

+7
source share
4 answers

You can lift partial function from Any to A to a function from Any to Option[A] .

So that nice syntax first defines a helper function:

 def lifted[A]( pf: PartialFunction[Any,A] ) = pf.lift 

Then make a profit:

 val f = lifted { case Type(i) => doStuff(i) } scala> f(2) res15: Option[Int] = None scala> f(Type(4)) res16: Option[Int] = Some(8) 

The doStuff method will only be called if the argument matches. And you can have several case sentences.

+7
source

The shortest way I can think of is to wrap the value in options and use the collect method:

 Option(x).collect { case Type(params) => doStuffWith(params) } 
+3
source

Using the link that @ phant0m gave to indicate:

 import PartialFunction.condOpt condOpt(x){ case Type(params) => doStuffWith(params) } 
+3
source

If this pattern often appears in your code, you should consider turning doSomeStuff into a Type method. Class classes in Scala are normal classes, and you should use object oriented functions when they make sense.

Otherwise, you can add a method at the top of your hierarchy, assuming that all of your case classes extend the line. For example:

 class Base { def whenType(f: (T1, T2) => Unit): Unit = this match { case Type(t1, t2) => f(t1, t2) case _ => () } } 

and then you can use x whenType doSomeStuff

0
source

All Articles