2012-07-12 12 views
12

¿Cómo puedo anular "toString" para hacer que este código Scala actúe como el siguiente código Java.Reemplazando el método toString en Scala Enumeration

Código de 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 

buscados comportamiento toString debe producir mismo resultado que el siguiente código 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 

Creo que estoy anulando el método "toString" incorrecto.

Respuesta

29

Primero, sí, está anulando el método incorrecto toString. Está anulando el método en el objeto BIT en sí mismo, que no es muy útil.

En segundo lugar, esto se hace mucho más fácil simplemente haciendo

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

A continuación, puede hacer

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

Si desea establecer el valor y la cadena que puede hacerlo de esta manera:

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 
Cuestiones relacionadas