Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala pattern match against a Java enum type

Tags:

enums

scala

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?

like image 334
joesan Avatar asked May 06 '26 21:05

joesan


1 Answers

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.

like image 82
sksamuel Avatar answered May 09 '26 01:05

sksamuel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!