如何覆盖“toString”以使此 Scala 代码的行为类似于以下 Java 代码。
Scala 中的代码
object BIT extends Enumeration {
type BIT = Value
val ZERO, ONE, ANY = Value
override def toString() =
this match {
case ANY => "x "
case ZERO=> "0 "
case ONE => "1 "
}
}
val b = ONE
println(ONE) // returns ONE
想要的 toString 行为应该产生与以下 Java 代码相同的输出。
public enum BIT {
ZERO, ONE, ANY;
/** print BIT as 0,1, and X */
public String toString() {
switch (this) {
case ZERO:
return "0 ";
case ONE:
return "1 ";
default://ANY
return "X ";
}
}
}
BIT b = ONE;
System.out.println(b); // returns 1
我想我覆盖了错误的“toString”方法。