Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get values of all variables in a case class without using reflection

Tags:

scala

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.

like image 476
aa8y Avatar asked Dec 02 '22 13:12

aa8y


1 Answers

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.

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
like image 183
0__ Avatar answered Dec 04 '22 04:12

0__