Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic customisation of case class ToString [duplicate]

Tags:

scala

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
)
like image 523
Sebastien Lorber Avatar asked Jul 05 '13 09:07

Sebastien Lorber


1 Answers

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))
like image 121
rlegendi Avatar answered Sep 28 '22 09:09

rlegendi