6

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.

Community
  • 1
  • 1
rtpg
  • 2,419
  • 1
  • 18
  • 31

4 Answers4

7

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.

paradigmatic
  • 40,153
  • 18
  • 88
  • 147
3

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) }
Kim Stebel
  • 41,826
  • 12
  • 125
  • 142
3

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

import PartialFunction.condOpt

condOpt(x){ case Type(params) => doStuffWith(params) }
Luigi Plinge
  • 50,650
  • 20
  • 113
  • 180
0

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

Otherwise, you could add a method at the top of your hierarchy, assuming all your case classes extend a common trait. 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

Iulian Dragos
  • 5,692
  • 23
  • 31