gpt4 book ai didi

scala - 在不使用反射的情况下获取案例类中所有变量的值

转载 作者:行者123 更新时间:2023-12-03 18:25:41 25 4
gpt4 key购买 nike

有没有一种简单的方法可以在不使用反射的情况下获取案例类中所有变量的值。我发现反射很慢,不应该用于大规模应用程序中的重复性任务。

我想要做的是覆盖 toString方法,以便它以在案例类中定义的相同顺序返回案例类中所有字段的制表符分隔值。

最佳答案

What I want to do is override the toString method such that it returns tab-separated values of all fields in the case class in the same order they've been defined in there.



像这样?
trait TabbedToString {
_: Product =>

override def toString = productIterator.mkString(s"$productPrefix[", "\t", "]")
}

编辑:说明—我们使用 self-type在这里,你也可以写 this: Product =>self: Product => .与继承不同,它只是声明这种类型( TabbedToString )必须混合到 Product 中。 ,因此我们可以调用 productIteratorproductPrefix .所有案例类都自动继承 Product特征。

用例:
case class Person(name: String, age: Int) extends TabbedToString

Person("Joe", 45).toString

关于scala - 在不使用反射的情况下获取案例类中所有变量的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33789490/

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