【问题标题】:Whats the best way to restore the default implementation of a case class toString恢复案例类 toString 的默认实现的最佳方法是什么
【发布时间】:2020-01-20 12:36:32
【问题描述】:

假设我做了以下事情:

trait A {
    val i: Int
    override def toString = s"A($i)"
}

case class B(i: Int, j: Int) extends A

println(B(2, 3))

这会给我输出:

A(2)

有没有一种方法可以让 B.toString 恢复为案例类的默认 toString 而无需我显式编写:

override def toString = s"B($i,$j)"

【问题讨论】:

标签: scala


【解决方案1】:

曾经是

override def toString = scala.runtime.ScalaRunTime._toString(this)

但该对象 在 2.12 中被删除 编辑:它只是从 ScalaDoc 中删除,但仍然存在。

为了避免依赖ScalaRunTime._toString,你可以自己定义:

def _toString(x: Product): String =
  x.productIterator.mkString(x.productPrefix + "(", ",", ")")

【讨论】:

  • 谢谢!由于某种原因在 Scaladoc 中找不到它scala-lang.org/api/2.12.0/scala/index.html?search=scalaruntime
  • 不在ScalaDoc中的原因在代码中有解释:The object ScalaRunTime provides support methods required by the scala runtime. All these methods should be considered outside the API and subject to change or removal without notice.
【解决方案2】:

也许

trait A {
  val i: Int
  override def toString = this match {
    case p: Product => scala.runtime.ScalaRunTime._toString(p)
    case _ => s"A($i)"
  }
}

case class B(i: Int, j: Int) extends A

class Foo extends A {
  override val i = 42
}

B(2, 3)
new Foo

哪个输出

res0: B = B(2,3)
res1: Foo = A(42)

【讨论】:

    猜你喜欢
    • 2020-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多