I have a Java enum type that has some Strings and I want to pattern match against in. Here is what I have done so far:
public enum MyEnum {
YEAR, MONTH;
}
In my scala function, I do the following:
timePeriod.toUpperCase match {
case MyEnum.YEAR.name => doSomething
case MyEnum.MONTH.name => doSomething
}
When I compile, I get the following error:
stable identifier required, but YEAR.name found
It is not informative enough for me to understand the root cause of the error. Any ideas?
You can't have method calls as clauses in a match, because the result of the method may differ. We know in this case it doesn't but there's no way to indicate to the compiler that a method call is constant.
You could do this:
timePeriod.toUpperCase match {
case period if period == MyEnum.YEAR.name =>
case period if period == MyEnum.MONTH.name =>
}
Which is a bit more verbose. Someone else may have a shorter and better suggestion.
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