如何打印课程'没有覆盖的toString中的var字段?

时间:2015-09-11 20:50:48

标签: scala tostring

我有以下课程:

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

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

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

1 个答案:

答案 0 :(得分:2)

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