Possible Duplicate:
Scala: short form of pattern matching that returns Boolean
In my scala code I'm finding myself often writing things like the following:
x match{
case Type(params) => doStuffWith(params)
case _ => /* do nothing*/
}
Is there already some predefined operator to do this? I think it would be much clearer if I could write things like:
if( x match Type(params)) {
doStuffWith(params)
}
essentially avoiding the weird otherwise case. I've also had other situations where being able to verify if something matches a pattern in an inline fashion would save me an extra pair of braces.
I know this sort of thing might only be more useful when writing more iterative code, but Scala seems to have so many hidden features I was wondering whether someone has a simple solution for this.
You could lift
a partial function from Any
to A
into a function from Any
to Option[A]
.
To make the syntax nice first define an helper function:
def lifted[A]( pf: PartialFunction[Any,A] ) = pf.lift
Then, make 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 be called only if the argument matches. And you can have several case clauses.
The shortest way I can think of is to wrap the value in an option and use the collect method:
Option(x).collect { case Type(params) => doStuffWith(params) }
Using the link that @phant0m gave, to spell it out:
import PartialFunction.condOpt
condOpt(x){ case Type(params) => doStuffWith(params) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With