【问题标题】:How to print out a classes' var fields in toString without override?如何在不覆盖的情况下在 toString 中打印出类的 var 字段?
【发布时间】:2015-09-11 20:50:47
【问题描述】:

我有以下课程:

case class Info(ticker: String, countryCode: String) {

  var companyName: String = _
  var marketPlace: String = _
  var countryName: String = _
  var tierId: Int = _
}

当我执行 info.toString 时,它只打印出股票代码和国家代码。如何在不手动覆盖 toString 方法的情况下打印出其他字段?

【问题讨论】:

  • 你为什么反对覆盖toString
  • 我只是想避免添加额外的代码行...
  • 以将默认字段设置为null?为代价

标签: scala tostring


【解决方案1】:

只需在案例类中提供额外字段作为条目,但将它们标记为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)

【讨论】:

  • 另一种方式也是如此 - 在这种情况下,_ 转换为 null 用于 String 类型和 0 用于 Int 类型。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-31
  • 2012-01-11
  • 1970-01-01
  • 2016-11-17
  • 1970-01-01
相关资源
最近更新 更多