Scala3枚举方法覆盖
有没有办法像在 Java 中一样覆盖 Scala 3 枚举中的方法?
public enum Test {
ONE {
@Override
public int calc() {
return 1;
}
},
TWO {
@Override
public int calc() {
return 2;
}
};
public abstract int calc();
}
我试过这样的事情,但没有结果。在文档中也没有找到关于枚举方法覆盖的任何内容。
enum Test {
def calc(): Int ={
0
}
case One
override def calc(): Int ={
1
}
case Two
override def calc(): Int ={
2
}
}
也许有另一种方法可以实现类似的功能?
回答
该enum是密封的,所以它不能在事后进行扩展,所以没有理由去override任何东西。只需在一个地方收集所有案例,而不是多个override-methods,编写一个涵盖所有案例的单一方法:
enum A:
case X(x: Int)
case Y(y: String)
def foo: String = this match {
case X(x) => s"X = ${x}"
case Y(y) => y
}
val x = new A.X(42)
val y = new A.Y("y")
println(x.foo) // X = 42
println(y.foo) // y
- @AndreiYusupau I'd argue that "yes", because 1. One wouldn't have to duplicate the `override def calc(): Int ={`-signature for each case class. 2. `match` is the natural way to work with enums, that's how they are supposed to be used. There is no need to deviate from the standard `match-case` in the declaration of `enum` itself.