Simple iterations over case class fields

I am trying to write a generic method for iterating the fields of case fields:

case class PriceMove(price: Double, delta: Double)

def log(pm : PriceMove) { info("price -> " + price + " delta -> " + delta)}

I need to make log capable of handling any case class. What should be the type of argument for log to process only class classes and the actual general iterative field code?

+6
scala case-class
source share
2 answers

Well, given the two questions I attached to the question, here is what I used:

 object Implicits { implicit class CaseClassToString(c: AnyRef) { def toStringWithFields: String = { val fields = (Map[String, Any]() /: c.getClass.getDeclaredFields) { (a, f) => f.setAccessible(true) a + (f.getName -> f.get(c)) } s"${c.getClass.getName}(${fields.mkString(", ")})" } } } case class PriceMove(price: Double, delta: Double) object Test extends App { import Implicits._ println(PriceMove(1.23, 2.56).toStringWithFields) } 

This gives:

 PriceMove(price -> 1.23, delta -> 2.56) 
+9
source share

I am afraid that there is no easy way to achieve what you need, because you cannot easily get the field names from the case class, as described here: Reflection on a Scala case class and General case class ToString setting .

You can try using reflection (although you can guarantee the order of the fields) or tools.nsc.interpreter.ProductCompletion , but both solutions are much more complicated than you really expected.

+1
source share

All Articles