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.
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

