0

假设我定义了以下枚举:

import enumeratum._
import enumeratum.EnumEntry.Lowercase

import scala.collection.immutable

sealed trait Day extends EnumEntry with Lowercase

object Day extends Enum[Day]{
  case object MON extends Day
  case object TUE extends Day
  case object WED extends Day
  /* ... */
  override def values: immutable.IndexedSeq[Day] = findValues
}
println(Day.Mon)           // MON, but I would like to see mon instead
println(Day.Mon.entryName) // mon

我想覆盖Day.toString以返回条目名称而不是类名称。但似乎不是那么直观。

我试过的:

  1. 手动覆盖toString返回entryName
sealed trait Day extends EnumEntry with Lowercase {
  override def toString: String = entryName
}

但它会产生 StackOverflowError (与惰性验证有关):

Exception in thread "main" java.lang.StackOverflowError
    at example.Day$MON$.enumeratum$EnumEntry$$stableEntryName(Day.scala:17)
    at enumeratum.EnumEntry.entryName(EnumEntry.scala:21)
    at enumeratum.EnumEntry.entryName$(EnumEntry.scala:21)
    at example.Day$MON$.enumeratum$EnumEntry$Lowercase$$super$entryName(Day.scala:17)
    at enumeratum.EnumEntry$Lowercase.enumeratum$EnumEntry$Lowercase$$stableEntryName(EnumEntry.scala:122)
    at enumeratum.EnumEntry$Lowercase.enumeratum$EnumEntry$Lowercase$$stableEntryName$(EnumEntry.scala:122)
    at example.Day$MON$.enumeratum$EnumEntry$Lowercase$$stableEntryName$lzycompute(Day.scala:17)
    at example.Day$MON$.enumeratum$EnumEntry$Lowercase$$stableEntryName(Day.scala:17)
    at enumeratum.EnumEntry$Lowercase.entryName(EnumEntry.scala:120)
    at enumeratum.EnumEntry$Lowercase.entryName$(EnumEntry.scala:120)
    at example.Day$MON$.entryName(Day.scala:17)
    at example.Day.toString(Day.scala:13)
    at example.Day.toString$(Day.scala:13)
    at example.Day$MON$.toString(Day.scala:17)
    at enumeratum.EnumEntry.enumeratum$EnumEntry$$stableEntryName(EnumEntry.scala:23)
    at enumeratum.EnumEntry.enumeratum$EnumEntry$$stableEntryName$(EnumEntry.scala:23)
    at example.Day$MON$.enumeratum$EnumEntry$$stableEntryName$lzycompute(Day.scala:17)
    at example.Day$MON$.enumeratum$EnumEntry$$stableEntryName(Day.scala:17)
  1. 指定super要使用的确切方法:

sealed trait Day extends EnumEntry with Lowercase {
  override def toString: String = super[Lowercase].entryName
}

但还是国企。

  1. 我知道手动覆盖条目名称是可能的,但它需要编写样板代码:

abstract class Day(override val entryName: String) extends EnumEntry {
  override def toString: String = entryName
}

object Day extends Enum[Day]{
  case object MON extends Day("mon")
  case object TUE extends Day("tue")
  case object WED extends Day("wed")
  /* ... */
  override def values: immutable.IndexedSeq[Day] = findValues
}
  1. 它适用于StringEnum但同样,我将需要为文字编写样板代码。
4

0 回答 0