如何在不覆盖的情况下打印出 toString 中的 类' var 字段?
How to print out a classes' var fields in toString without override?
我有以下 class:
case class Info(ticker: String, countryCode: String) {
var companyName: String = _
var marketPlace: String = _
var countryName: String = _
var tierId: Int = _
}
当我执行 info.toString 时,它只打印出代码和国家代码。如何在不手动覆盖 toString 方法的情况下打印出其他字段?
在 class 的情况下,只需提供额外的字段作为条目,但将它们标记为 var
:
case class Info(
ticker: String,
countryCode: String,
var companyName: String = null,
var marketPlace: String = null,
var countryName: String = null,
var tierId: Int = 0
)
将它们添加到生成的 toString
:
scala> Info("TK", "US")
res1: Info = Info(TK,US,null,null,null,0)
但您仍然可以改变您需要的那些:
scala> res1.companyName = "Cool Co."
res1.companyName: String = Cool Co.
scala> res1
res2: Info = Info(TK,US,Cool Co.,null,null,0)
我有以下 class:
case class Info(ticker: String, countryCode: String) {
var companyName: String = _
var marketPlace: String = _
var countryName: String = _
var tierId: Int = _
}
当我执行 info.toString 时,它只打印出代码和国家代码。如何在不手动覆盖 toString 方法的情况下打印出其他字段?
在 class 的情况下,只需提供额外的字段作为条目,但将它们标记为 var
:
case class Info(
ticker: String,
countryCode: String,
var companyName: String = null,
var marketPlace: String = null,
var countryName: String = null,
var tierId: Int = 0
)
将它们添加到生成的 toString
:
scala> Info("TK", "US")
res1: Info = Info(TK,US,null,null,null,0)
但您仍然可以改变您需要的那些:
scala> res1.companyName = "Cool Co."
res1.companyName: String = Cool Co.
scala> res1
res2: Info = Info(TK,US,Cool Co.,null,null,0)