Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding toString method in Scala Enumeration

Tags:

enums

scala

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.

like image 795
Suheil Avatar asked Jul 12 '12 17:07

Suheil


2 Answers

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"
like image 59
Dan Simon Avatar answered Nov 01 '22 05:11

Dan Simon


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
like image 22
lockwobr Avatar answered Nov 01 '22 07:11

lockwobr