This is related to the following question: In scala, how to turn object's values into Map[String, String]?
In fact, I have almost exactly the same problem. However, the solution given in the accepted answer runs around 50x slower than productIterator
(which returns only the values of the fields) when iterating 1000 times on my machine (or manually writing a function to return the list of (key, value) pairs). Is there a reasonably performant and clean way of getting the names of the fields of a case class in Scala? It seems strange to me that the core language would provide a performant reflection-like way of getting the values, but not the field names.
If you write and compile a case class, you can browse through the generated byte code and you will notice that the field names are not hardcoded anywhere into a method of the class. This means you must use reflection for finding out about these names. And reflective lookup is unfortunately expensive.
With the
productIterator
, there is however an approach for avoiding reflection. Any case class implements theProduct
trait which defines a methodObject productElement(int)
which will return the value of the field at a given index. Other than the field names, this information is hardcoded into a case class method. By internally using this method, theproductIterator
method avoids reflection and can be executed efficiently.Bottom line: While reflective invocation is not so expensive, reflective lookup is. If you need the field name information, you should therefore only lookup the information once and cache the results for later reuse.