如何为Enumeratum IntEnumEntry使用withName()方法

时间:2018-05-21 22:14:59

标签: scala enums

我目前在Scala 2.12.6中使用Enumeratum 1.5.13。我有以下定义:

sealed abstract class PartOfSpeech(val value: Int) extends IntEnumEntry
case object PartOfSpeech extends IntEnum[PartOfSpeech] {
  val values = findValues

  case object Noun        extends PartOfSpeech(0)
  case object Adjective   extends PartOfSpeech(1)
  case object Verb        extends PartOfSpeech(2)
  case object Adverb      extends PartOfSpeech(3)
  case object Numeric     extends PartOfSpeech(4)
  case object Exclamation extends PartOfSpeech(5)
  case object Preposition extends PartOfSpeech(6)
  case object Pronoun     extends PartOfSpeech(7)
  case object Conjunction extends PartOfSpeech(8)
  case object Determiner  extends PartOfSpeech(9)
  case object Article     extends PartOfSpeech(10)
}

然后,当我尝试使用withName()这样的方法时:

val pos = PartOfSpeech.withName("Noun")

...我收到一个编译错误,指出找不到方法withName。所以,鉴于我没有看到Enumeratum的ScalaDoc(至少我找不到它们),我不知道如何在不挖掘其源代码的情况下回答这个问题。在投入时间之前,我想我可能会看到其他人是否有一个简单和/或明显的解决方案。

1 个答案:

答案 0 :(得分:0)

据我所知,实现这项工作的唯一方法是让我自己在case object内实施。所以,我补充说:

private val enumEntryByClassSimpleNameLowerCase: Map[String, PartOfSpeech] =
  values.map(enumEntry => (enumEntry.getClass.getSimpleName.takeWhile(_ != '$').toLowerCase, enumEntry)).toMap

def withName(value: String): Option[PartOfSpeech] =
  enumEntryByClassSimpleNameLowerCase.get(value.toLowerCase)

感觉就像是黑客。我当然希望Enumeratum里面有一些东西,我只是想念。如果有更好的方法来实现这一结果,请告诉我。我使用enums一大堆。因此,这个样板将在我的代码库中泄漏。