Scala 2.10 reflection, how do I extract the field values from a case class, i.e. field list from case class

MethodSymbol has an isCaseAccessor method that allows you to do precisely this: def getMethods[T: TypeTag] = typeOf[T].members.collect { case m: MethodSymbol if m.isCaseAccessor => m }.toList Now you can write the following: scala> case class Person(name: String, age: Int) defined class Person scala> getMethods[Person] res1: List[reflect.runtime.universe.MethodSymbol] = List(value age, value name) And you get only … Read more

Scala case class inheritance

My preferred way of avoiding case class inheritance without code duplication is somewhat obvious: create a common (abstract) base class: abstract class Person { def name: String def age: Int // address and other properties // methods (ideally only accessors since it is a case class) } case class Employer(val name: String, val age: Int, … Read more

Scala Macros: Making a Map out of fields of a class in Scala

Note that this can be done much more elegantly without the toString / c.parse business: import scala.language.experimental.macros abstract class Model { def toMap[T]: Map[String, Any] = macro Macros.toMap_impl[T] } object Macros { import scala.reflect.macros.Context def toMap_impl[T: c.WeakTypeTag](c: Context) = { import c.universe._ val mapApply = Select(reify(Map).tree, newTermName(“apply”)) val pairs = weakTypeOf[T].declarations.collect { case m: MethodSymbol … Read more