Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to ignore a non-matching case?

Tags:

scala

If I have a match expression, how can I make it automatically ignore a non-match without explicitly doing case _ =>? Is there a way to create a function that does something like this maybe?

like image 672
ryeguy Avatar asked Mar 26 '11 20:03

ryeguy


2 Answers

You need a generic way to handle "ignoring". Options, among other classes, provide this (among other things). So you can:

val i = 7
Some(i) collect {
  case 3 => "Yay!"
  case 5 => "Boo!"
}

to get None (typed as an Option[String]). So basically, if you change x match to Some(x) collect you get the functionality you want. It is better to do this when one is comfortable with handling options.

like image 128
Rex Kerr Avatar answered Oct 06 '22 00:10

Rex Kerr


Write a generic matcher:

object Match {
    def default: PartialFunction[Any, Unit] = { case _ => }
    def apply[T](x: T)(body: PartialFunction[T, Unit]) = (body orElse default)(x)
}

Example:

scala> 1 to 5 foreach (Match(_) {
     |   case 2 => println("two")
     |   case 3 => println("three")
     | }
     | )
two
three

You might be interested too in PartialFunction's companion object's methods cond and condOpt.

like image 31
Daniel C. Sobral Avatar answered Oct 06 '22 00:10

Daniel C. Sobral