Home:ALL Converter>Avoiding MatchError when matching over subset of possible values

Avoiding MatchError when matching over subset of possible values

Ask Time:2016-09-10T05:37:36         Author:SamTebbs33

Json Formatter

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?

Author:SamTebbs33,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/39420069/avoiding-matcherror-when-matching-over-subset-of-possible-values
yy