我想写一个“toSource”函数,它将生成基本案例类的源代码。例如,我想:
case class Person(name: String, age: Int)
val bob = Person("Bob", 20)
println(toSource(bob)) // Should print """Person("Bob", 20)"""
“toString”函数几乎给了我想要的东西,但它会删除字符串周围的引号:
println(bob.toString) // Prints """Person(Bob, 20)"""
任何想法如何做到这一点?
答案 0 :(得分:6)
您可以利用案例类混合特征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)"""