SamTebbs33 SamTebbs33 - 2 months ago 10
Scala Question

Avoiding MatchError when matching over subset of possible values

I was wondering if it's possible to match over a subset of the possible values without having a

MatchError
thrown.

def foo(bar: String): Int = bar match {
case "x" => 0
case "y" => 1
case _ => -1
}


In the above example, I understand that you absolutely have to match over all possible values, as the method has to return something.

def foo(bar: String): Unit = {
bar match {
case "x" => isX()
case "y" => isY()
}
}


However in the above example, I don't feel that it would be necessary to match all possible values, since the method doesn't depend on the result of the match, since it is only calling methods. If
bar
was some value other than "x" or "y" then a
MatchError
would be thrown, which is extremely annoying and avoiding this would require adding a pointless
case _ =>
clause.

It would be so much more convenient and concise if you didn't have to match over all possible values if you just wanted to do something, rather than return something. Is this possible?

Answer

So what you want is a partial function where a failure to match does nothing. That's pretty much the definition of collect except we don't have a collection. That's easily fixed, resulting in

def foo(bar: String): Unit = {
  Some(bar) collect {
      case "x" => isX()
      case "y" => isY()
  }
}

which does what you want.