16

On this link: https://stackoverflow.com/a/4055850/82609

It explains that

case class Person(name: String, age: Int) {
   override def productPrefix = "person: "
}

// prints "person: (Aaron,28)" instead of "Person(Aaron, 28)"
println(Person("Aaron", 28)) 

Is there a way to do something like mixing the case class with some trait do provide a better ToString than the default one?

I don't really like to not have the field names printed, and for large case classes it is sometimes hard to read the logs.

Is it possible to have an output like this?

Person(
  name="Aaron",
  age=28
)
Community
  • 1
  • 1
Sebastien Lorber
  • 89,644
  • 67
  • 288
  • 419

1 Answers1

14

How about overriding toString()? You can do that even in a specific trait (or each time at the level of the case class and calling an object function).

trait CustomToString {
  override def toString() = "do some reflection magic here"
}

case class Person(name: String, age: Int) extends CustomToString

println(Person("Belä", 222))
rlegendi
  • 10,466
  • 3
  • 38
  • 50
  • 1
    this is not a generic solution and I'd like to reuse it in many case classes – Sebastien Lorber Jul 05 '13 at 14:30
  • How about the updated answer? – rlegendi Jul 05 '13 at 15:08
  • I'll accept, but some answers are more appropriate in the "possible duplicate" link provided here: http://stackoverflow.com/questions/15718506/scala-how-to-print-case-classes-like-pretty-printed-tree – Sebastien Lorber Jul 05 '13 at 15:38
  • 1
    Yeah, surely you can do more with external libraries. First hit on Google for instance was this which is definitely what you're looking for: https://github.com/ymasory/labeled-tostring – rlegendi Jul 05 '13 at 15:54
  • 1
    I posted a solution using reflection at the bottom of: https://issues.scala-lang.org/browse/SI-3967 – piotr Feb 21 '16 at 13:20