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

Scala带参数化值的Enumeration实现可行性问询

Great question! The standard Scala Enumeration doesn't support dynamic, parameterized values like you're trying to do with Other(value)—since all enumeration values are fixed when the enum object is initialized. But don't worry, we can achieve exactly what you want using sealed traits with case objects/classes, which is the more flexible, idiomatic approach in Scala for this kind of scenario.

Solution: Sealed Trait + Case Objects/Classes

Instead of relying on Scala's built-in Enumeration, we'll define a sealed trait (to restrict all possible implementations to this file) alongside fixed case objects for known values, and a case class for the dynamic "Other" value:

sealed trait Animal {
  def toString: String
}

// Fixed, predefined animal types
case object Dog extends Animal {
  override def toString: String = "dog"
}

case object Cat extends Animal {
  override def toString: String = "cat"
}

// Dynamic "Other" type that holds a custom string value
case class Other(value: String) extends Animal {
  override def toString: String = value
}

object Animal {
  // Factory method to create the correct Animal instance
  def create(value: String): Animal = value.toLowerCase match {
    case "dog" => Dog
    case "cat" => Cat
    case customValue => Other(customValue)
  }
}

Usage Examples

This implementation matches exactly the behavior you're looking for:

Animal.create("dog")       // Returns the Dog case object
Animal.create("giraffe")   // Returns Other("giraffe")
Animal.create("dog").toString    // Outputs "dog"
Animal.create("giraffe").toString // Outputs "giraffe"

Bonus: Pattern Matching Support

One huge advantage of this approach over Enumeration is that it plays nicely with Scala's pattern matching, making it easy to handle each case explicitly:

def describeAnimal(animal: Animal): String = animal match {
  case Dog => "A loyal canine"
  case Cat => "A curious feline"
  case Other(name) => s"An unknown animal called $name"
}

describeAnimal(Animal.create("giraffe")) // Returns "An unknown animal called giraffe"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:49:06