Scala pattern matching Java enum value
You can pattern match on Java enums, but you can't call methods in the destructuring part of the match. So this works:
j match { case Jenum.FOO => "yay"; case _ => "boo" }
if j
is an instance of your Java enum (cleverly labeled Jenum
).
You can however do something like this:
"foo" match {
case s if s == Jenum.FOO.getValue => "yay"
case _ => "boo"
}
Or you can convert your string to the enum first:
Jenum.values.find(_.getValue == "foo") match {
case Some(Jenum.FOO) => "yay"
case _ => "boo"
}
(you might also want to unwrap the option first to avoid repeating Some(...)
so many times).
For reference, this is the test enum I used (Jenum.java):
public enum Jenum {
FOO("foo"), BAR("bar");
private final String value;
Jenum(String value) { this.value = value; }
public String getValue() { return value; }
}
You receive the comment "method". So scala does not evaluates your function. It tried to call unapply on method.
You can implement something like (in MyEnum class):
public static MyEnum fromText(String text) {
for (MyEnum el : values()) {
if (el.getValue().equals(text)) {
return el;
}
}
return null;
}
And then
MyEnum.fromText("foo") match{
case FOO => ..
}
You can't use a method call result as a pattern. Instead just write
if (result == YourEnum.FOO.getValue()) {
...
} else if {
...
}
or
try {
val resultAsEnum = YourEnum.valueOf(result)
resultAsEnum match {
case YourEnum.FOO => ...
...
}
} catch {
case e: IllegalArgumentException => // didn't correspond to any value of YourEnum
}