aa8y
aa8y

Reputation: 3942

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

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.

Upvotes: 4

Views: 2034

Answers (2)

0__
0__

Reputation: 67280

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

Upvotes: 13

Archeg
Archeg

Reputation: 8462

You could use its extractor:

case class A(val i: Int, val c: String) {
  override def toString = A.unapply(this).get.toString // TODO: apply proper formatting.
}

val a = A(5, "Hello world")
println(a.toString) 

Upvotes: 5

Related Questions