You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Enumeratum IntEnumEntry中使用withName()方法?

解决Enumeratum IntEnum找不到withName方法的问题

嘿,这个问题其实是因为你用的是IntEnum特质——它是专门为基于整数值的枚举设计的,默认只提供了根据整数查找的withValue方法,而withName是字符串类型枚举(直接继承Enum特质)才自带的方法。

给你两个简单可行的解决方案,按需选择:

方案1:自定义withName方法(按名称查找)

如果你确实需要通过枚举的名称(比如"Noun")来获取实例,可以在PartOfSpeech对象里手动实现这个方法:

case object PartOfSpeech extends IntEnum[PartOfSpeech] {
  val values = findValues
  
  // 新增自定义的withName方法
  def withName(name: String): PartOfSpeech = {
    values.find(_.productPrefix == name)
      .getOrElse(throw new IllegalArgumentException(s"No PartOfSpeech named '$name' exists"))
  }

  // 你的枚举实例...
  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)
}

这样你原来的PartOfSpeech.withName("Noun")就能正常工作了,productPrefix会返回case object的准确名称,比直接用toString更可靠。

方案2:使用IntEnum自带的withValue方法(按数值查找)

如果你的需求其实是通过整数值来获取枚举实例,那直接用IntEnum提供的withValue就好,这也是它设计的初衷:

val pos = PartOfSpeech.withValue(0) // 会返回Noun实例

内容的提问来源于stack exchange,提问作者chaotic3quilibrium

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:02:56