Duc*_*Duc 10 java regex enums scala pattern-matching
我有我的java枚举,例如:FOO("foo")
,BAR("bar")
...我有一个getValue()
方法来返回值"foo"
和"bar"
枚举,这必须是Java.
另一方面,我必须在Scala中匹配:
result match {
case "foo" =>
Run Code Online (Sandbox Code Playgroud)
我想做:
result match {
case Enum.FOO.getValue() =>
Run Code Online (Sandbox Code Playgroud)
我收到此错误:
method getValue is not a case class constructor, nor does it have an
unapply/unapplySeq method
Run Code Online (Sandbox Code Playgroud)
我不太清楚这里发生了什么,因为我的getValue()
方法返回了一个String
为什么我不能用它来进行模式匹配?谢谢
Rex*_*err 13
您可以在Java枚举上进行模式匹配,但不能在匹配的解构部分中调用方法.这样可行:
j match { case Jenum.FOO => "yay"; case _ => "boo" }
Run Code Online (Sandbox Code Playgroud)
if j
是Java枚举的实例(巧妙标记Jenum
).
但是你可以这样做:
"foo" match {
case s if s == Jenum.FOO.getValue => "yay"
case _ => "boo"
}
Run Code Online (Sandbox Code Playgroud)
或者您可以先将字符串转换为枚举:
Jenum.values.find(_.getValue == "foo") match {
case Some(Jenum.FOO) => "yay"
case _ => "boo"
}
Run Code Online (Sandbox Code Playgroud)
(您可能还想先打开选项以避免重复Some(...)
这么多次).
作为参考,这是我使用的测试枚举(Jenum.java):
public enum Jenum {
FOO("foo"), BAR("bar");
private final String value;
Jenum(String value) { this.value = value; }
public String getValue() { return value; }
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6407 次 |
最近记录: |