The Labeled ToString project provides several traits you can mix into case classes in order to get
toString representations that include parameter labels. That means you get Person(name=John Doe,age=30) instead of Person(John Doe,30).
Here's a normal case class:
case class Person(name: String, age: Int) Person("John Doe", 30).toString //result is "Person(John Doe,30)"
Here's our labeled case class:
import com.yuvimasory.tostring._ case class Person(name: String, age: Int) extends LabeledToStringDef Person("John Doe", 30).toString //result is "Person(name=John Doe,age=30)"
labeled-tostring is hosted on Maven Central. You can add it as a dependency to your
build.sbt file. It is built for Scala 2.8.0 through 2.9.2.
libraryDependencies += "com.yuvimasory" %% "labeled-tostring" % "0.5.0"
com.yuvimasory.tostring package provides three traits:
LabeledToStringLazyVal. They override the default case class's
toString method with a
lazy val, respectively.
- If you're not sure which to use, start with
LabeledToStringDef, which works in all cases.
LabeledToStringValif you know the case class's parameters are either immutable (e.g., primitive types, immutable collections), or have string representations that never change (e.g., arrays).
LabeledToStringLazyValif you meet the criteria for
LabeledToStringValand want lazy initialization.
- Both of the
*Valtraits may run
toStringmuch faster after the first call, since the store the result. The cost is a bit of memory and a slow initial
- You must use
LabeledToStringDefif your case classes are Squeryl tables. If you don't Squeryl will generate bogus SQL.
Benchmarks are in a separate repository.
[info] benchmark ns linear runtime [info] CreateCaseClassPerson 6.66 = [info] CreateLabeledToStringValPerson 1262.54 ============================== [info] CreateLabeledToStringLazyValPerson 8.68 = [info] CreateLabeledToStringDefPerson 6.63 =
We don't have a good way to benchmark this presently.
[info] benchmark ns linear runtime [info] SubsequentToStringsOfCaseClassPerson 750 ======== [info] SubsequentToStringsOfLabeledToStringValPerson 146 = [info] SubsequentToStringsOfLabeledToStringLazyValPerson 185 == [info] SubsequentToStringsOfLabeledToStringDefPerson 2594 ==============================
- These traits produce unexpected strings in the REPL due to the way the REPL wraps code and mangles names.
- These traits do not work if you add bodies to your case classes (i.e., additional methods or fields).