gpt4 book ai didi

Scala:覆盖 toString 以便在字符串周围打印引号

转载 作者:行者123 更新时间:2023-12-04 18:46:39 27 4
gpt4 key购买 nike

我想编写一个“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)"""

任何想法如何做到这一点?

最佳答案

您可以利用 case 类混合在 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)"""

关于Scala:覆盖 toString 以便在字符串周围打印引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13148936/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com