A simple solution is to use a map:
case class Person(id: Int, name: String, age: Int)
val people: List[Person] = List(Person(2, "Angela", 31), Person(3, "Rick", 28))
val peopleByName: Map[String, Person] = people // List[Person]
.map(p => (p.name, p)) // List[(String, Person)]
.toMap // Map[String, Person]
or, starting with a Map
instead of a List
:
case class Person(id: Int, age: Int)
val peopleByName: Map[String, Person] = Map(
"Angela" -> Person(2, 31), // (String, Person)
"Rick" -> Person(3, 28) // (String, Person)
) // Map[String, Person]
However, if you want to define a member at runtime, then you'll have to extend the Dynamic
trait (code snippet from here, the import is mine (required, otherwise the compiler won't be happy)):
import scala.language.dynamics
class DynImpl extends Dynamic {
def selectDynamic(name: String) = name
}
scala> val d = new DynImpl
d: DynImpl = DynImpl@6040af64
scala> d.foo
res37: String = foo
scala> d.bar
res38: String = bar
scala> d.selectDynamic("foo")
res54: String = foo
If you really want to do this, then I suggest this implementation:
class DynamicPeople(peopleByName: Map[String, Person]) extends Dynamic {
def selectDynamic(name: String) = peopleByName(name)
}