17

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 ) 
0

1 Answer 1

15

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)) 
Sign up to request clarification or add additional context in comments.

5 Comments

this is not a generic solution and I'd like to reuse it in many case classes
How about the updated answer?
I'll accept, but some answers are more appropriate in the "possible duplicate" link provided here: stackoverflow.com/questions/15718506/…
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: github.com/ymasory/labeled-tostring
I posted a solution using reflection at the bottom of: issues.scala-lang.org/browse/SI-3967

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.