Get the values ​​of all variables in the case class without using reflection

Is there an easy way to get the values ​​of all the variables in the case class without using reflection. I found that reflection is slow and should not be used for repetitive tasks in large-scale applications.

What I want to do is redefine the method toStringso that it returns values ​​separated by tabs for all fields of the case class in the same order in which they were defined there.

+4
source share
2 answers

You can 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) 
+4
source

, toString, , , case , .

?

trait TabbedToString {
  _: Product =>

  override def toString = productIterator.mkString(s"$productPrefix[", "\t", "]")
}

: . self-type, this: Product => self: Product =>. , , (TabbedToString) Product, productIterator productPrefix. case Product.

:

case class Person(name: String, age: Int) extends TabbedToString

Person("Joe", 45).toString
+11

Source: https://habr.com/ru/post/1616432/


All Articles