Getting the parameters of a case class through Reflection

Viewed 3886

As a follow up of Matt R's question, as Scala 2.10 has been out for quite an amount of time, what would be the best way to extract the fields and values of a case class. Taking a similar example:

case class Colour(red: Int, green: Int, blue: String) {
  val other: Int = 42
} 

val RBG = Colour(1,3,"isBlue")

I want to get a list (or array or any iterator for that matter) that would have the fields declared in the constructor as tuple values like these:

[(red, 1),(green, 3),(blue, "isBlue")]

I know the fact that there are a lot of examples on the net regarding the same issue but as I said, I wanted to know what should be the most ideal way to extract the required information

2 Answers

Every case object is a product, therefore you can use an iterator to get all its parameters' names and another iterator to get all its parameters' values:

case class Colour(red: Int, green: Int, blue: String) {
  val other: Int = 42
}

val rgb = Colour(1, 3, "isBlue")

val names = rgb.productElementNames.toList  // List(red, green, blue)
val values = rgb.productIterator.toList     // List(1, 3, isBlue)

names.zip(values).foreach(print)            // (red,1)(green,3)(blue,isBlue)

By product I mean both Cartesian product and an instance of Product. This requires Scala 2.13.0; although Product was available before, the iterator to get elements' names was only added in version 2.13.0.

Notice that no reflection is needed.

Related