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?
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)"""
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With