Suheil
Suheil

Reputation: 173

Overriding toString method in Scala Enumeration

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.

Upvotes: 17

Views: 12280

Answers (2)

lockwobr
lockwobr

Reputation: 1511

If you want to set the value and the string you can do it like this:

scala> object BIT extends Enumeration {
     |   type BIT = Value
     |   val ZERO = Value(0, "0")
     |   val ONE = Value(1, "1")
     |   val ANY = Value("x")
     | }
defined module BIT

scala> BIT.ZERO.toString
res2: String = 0

scala> BIT.ZERO.id
res3: Int = 0

scala> BIT.ANY.id
res4: Int = 2

scala> BIT.ANY.toString
res5: String = x

Upvotes: 3

Dan Simon
Dan Simon

Reputation: 13137

First, yes you are overriding the wrong toString method. You're overriding the method on the BIT object itself, which is not very useful.

Second, you do this much easier by simply doing

object BIT extends Enumeration {
  type BIT = Value
  val ZERO = Value("0")
  val ONE = Value("1")
  val ANY = Value("x")
}

Then you can do

println(BIT.ONE) //prints "1"

Upvotes: 38

Related Questions