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?
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.
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
.
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