andyroo
andyroo

Reputation: 394

Pattern match a string to a field

I have a class that has some vals to it, I need a function that returns the vals based on a string passed in

case class AThing(name: String, description: String)

object AThing {

  val FIRST_THING = AThing("FIRST_THING", "A first thing desc")
  val SECOND_THING = AThing("SECOND_THING", "A second thing desc")
  val THIRD_THING = AThing("THIRD_THING", "A third thing desc")

}

Now I have the following solution:

def get(name: String): AThing = {

  name match {
    case "FIRST_THING"   => FIRST_THING
    case "SECOND_THING"  => SECOND_THING
    case "THIRD_THING"   => THIRD_THING
  }

}

Is there a better pattern for this.. I swear I remember seeing something along the lines of this:

def get(name: String): AThing = {
  name match {
    case `name` => AThing.`name`
    // OR
    case `name` => AThing.{{name}}
  }
}

Thanks.

Upvotes: 0

Views: 248

Answers (1)

Kolmar
Kolmar

Reputation: 14224

You can use Java reflection to get the field:

def get(name: String): AThing = 
  AThing.getClass.getDeclaredMethod(name).invoke(AThing).asInstanceOf[AThing]

As a method of object AThing you can also have it in this form:

object AThing {
  val FIRST_THING = ???
  // ... other things

  def get(name: String) = 
    this.getClass.getDeclaredField(name).get(this).asInstanceOf[AThing]
}

Or with Scala reflection:

import scala.reflect.runtime.universe._
import scala.reflect.runtime.currentMirror
def get(name: String) = 
  currentMirror.reflect(AThing)
               .reflectField(typeOf[AThing.type].member(TermName(name)).asTerm)
               .get.asInstanceOf[AThing]

To add more safety you can make it return an Option:

def getOption(name: String): Option[AThing] = util.Try(get(name)).toOption

But also consider modelling this concept with a Map:

object AThing {
  val things: Map[String, AThing] = Seq(
    AThing("FIRST_THING", "A first thing desc"),
    AThing("SECOND_THING", "A second thing desc"),
    AThing("THIRD_THING", "A third thing desc")
  ).map(thing => thing.name -> thing).toMap
}

Then you can use AThing.things("FIRST_THING") to get a thing by name, or to get an Option: AThing.things.get("FIRST_THING").

Upvotes: 3

Related Questions