Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does scala have a "test-if-match" operator? [duplicate]

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.

like image 260
rtpg Avatar asked Sep 04 '12 12:09

rtpg


3 Answers

You could lifta 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.

like image 176
paradigmatic Avatar answered Oct 17 '22 07:10

paradigmatic


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) }
like image 38
Kim Stebel Avatar answered Oct 17 '22 07:10

Kim Stebel


Using the link that @phant0m gave, to spell it out:

import PartialFunction.condOpt

condOpt(x){ case Type(params) => doStuffWith(params) }
like image 3
Luigi Plinge Avatar answered Oct 17 '22 07:10

Luigi Plinge