Overriding toString method in Scala Enumeration

Viewed 11464

How can I override "toString" to make this Scala code acts like the following Java code.

Code in 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

Wanted toString behaviour should produce same output as the following Java code.

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

I think I am overriding the wrong "toString" method.

2 Answers
Related