I am trying to model (in my Scala application) a list of options presented in my web page and am scratching my head coming up with a solution for mapping a String
value posted from the client to it's corresponding object in the backend.
eg. Let's say it is a list of Animals
and the user can choose 1 which gets posted to the backend.
Animals
Polar Bear
Rabbit
Great White Shark
When a request comes in, I want to convert the Great White Shark String
to an Animal
but not sure on how best to match the
String
to the appropriate type in the backend.
So far I have this.
sealed abstract class Animal(val name: String)
case object GreatWhite extends Animal("Great White Shark")
case object PolarBear extends Animal("Polar Bear")
Which allows me to do this to match the String from the UI to it's corresponding case object in my Scala application.
def matcher(animal: String) = animal match {
case GreatWhite.name => GreatWhite
case PolarBear.name => PolarBear
}
Problem
If the List of Animal's grows long however, this matcher is going to be very cumbersome since I need to have a case
expression for every Animal
.
I would much appreciate any experienced Scala guys giving me a pointer on a more elegant solution.