Is there an easy way to get the values of all the variables in a case class without using reflection. I found out that reflection is slow and should not be used for repetitive tasks in large scale applications.
What I want to do is override the toString method such that it returns tab-separated values of all fields in the case class in the same order they've been defined in there.
What I want to do is override the
toStringmethod such that it returns tab-separated values of all fields in the case class in the same order they've been defined in there.
Like this?
trait TabbedToString {
_: Product =>
override def toString = productIterator.mkString(s"$productPrefix[", "\t", "]")
}
Edit: Explanation—We use a self-type here, you could also write this: Product => or self: Product =>. Unlike inheritance it just declares that this type (TabbedToString) must occur mixed into a Product, therefore we can call productIterator and productPrefix. All case classes automatically inherit the Product trait.
Use case:
case class Person(name: String, age: Int) extends TabbedToString
Person("Joe", 45).toString
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With