Case Class toString new behavior proposal (with implementation)

I found myself coming back to this thread a few times to copy-paste the pretty function by @olafurpg. For anyone else doing similar, here is that function wrapped up in a trait for easier consumption

trait PrettyProduct extends Product {
  override def toString: String = {
    this
      .productElementNames
      .zip(this.productIterator)
      .map { case (name, value) => s"$name=$value" }
      .mkString(this.productPrefix + "(", ", ", ")")
  }
}
final case class Apple(a: Int, b: String) extends PrettyProduct

println(Apple(a=3, b="hello")); // Apple(a=3, b=hello)
7 Likes