覆盖 Scala 枚举中的 toString 方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11457559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 04:21:23  来源:igfitidea点击:

Overriding toString method in Scala Enumeration

scalaenums

提问by Suheil

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

如何覆盖“toString”以使此 Scala 代码的行为类似于以下 Java 代码。

Code in Scala

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.

想要的 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

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

我想我覆盖了错误的“toString”方法。

回答by Dan Simon

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

首先,是的,您覆盖了错误的 toString 方法。您正在覆盖BIT对象本身的方法,这不是很有用。

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"

回答by lockwobr

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