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

如何在Scala 3中获取枚举实例的name名称?

Scala 3 获取枚举实例名称的方法

Scala 3 中所有枚举类型默认实现了 scala.reflect.Enum 特质,要拿到和 Java 枚举 name() 方法等效的实例名称字符串,直接调用 productPrefix 属性即可。

注意:默认情况下枚举的 toString 返回值和 productPrefix 一致,但如果手动重写了 toString 方法,前者的返回值会变化,productPrefix 则固定和枚举实例声明的名称完全一致,更贴合 Java name() 方法的语义。

基础用法示例

针对你给出的 Color 枚举:

enum Color:
  case Red, Green, Blue

获取名称的代码如下:

@main def test() =
  println(Color.Red.productPrefix)   // 输出 Red
  println(Color.Green.productPrefix) // 输出 Green
  println(Color.Blue.productPrefix)  // 输出 Blue

自定义名称实现

如果需要自定义枚举的显示名称,不需要修改默认的 productPrefix 逻辑,直接给枚举添加自定义字段即可,示例如下:

enum Color(val displayName: String):
  case Red extends Color("红色")
  case Green extends Color("绿色")
  case Blue extends Color("蓝色")

调用 Color.Red.displayName 即可拿到你自定义的显示名称。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 22:06:07