Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 758
emchristiansen Avatar asked Oct 30 '12 23:10

emchristiansen


1 Answers

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)"""
like image 169
0__ Avatar answered Nov 15 '22 03:11

0__