Search code examples
scalaserializationintrospection

Scala: Override toString so quotes are printed around strings


I'd like to write a "toSource" function that will generate the source code for basic case classes. For example, I'd like:

case class Person(name: String, age: Int)
val bob = Person("Bob", 20)
println(toSource(bob)) // Should print """Person("Bob", 20)"""

The "toString" function almost gives me what I want, but it drops the quotes around strings:

println(bob.toString) // Prints """Person(Bob, 20)"""

Any ideas how to do this?


Solution

  • You could exploit the fact that case classes mix in trait Product:

    def toSource(p: Product): String =
       p.productIterator.map {
          case s: String => "\"" + s + "\""
          case other => other.toString
       } mkString (p.productPrefix + "(", ", ", ")")
    
    toSource(Person("Bob", 20))  // yields """Person("Bob", 20)"""