Case Class toString new behavior proposal (with implementation)

The PR https://github.com/scala/scala/pull/6972 has been merged adding the method productElementName to case classes. This means that it’s possible to implement the functionality propsed here without macros or runtime reflection

  def pretty(p: Product): String =
    p.productElementNames.zip(p.productIterator)
     .map { case (name, value) => s"$name=$value" }
     .mkString(p.productPrefix + "(", ", ", ")")

pretty(User("Susan", 42))
// User(name=Susan, age=42)

I started a discussion on adding such a pretty-printing function to the standard library https://github.com/scala/scala/pull/6972#issuecomment-411360323

7 Likes