Scala 中继承大小写 class 的 toString 方法

toString method for inherited case class in Scala

我在 Scala 中为 case-classes 调用 toString 方法时遇到了一些不一致的问题。第一个代码示例:

case class Person(name: String, age: Int)
val jim = Person("jim", 42)
println(jim)

输出:Person(jim,42)

对于下一个代码示例,我使用了一个扩展 Exception:

的案例 class
case class JimOverslept(msg: String) extends Exception
try {
  throw JimOverslept(msg = "went to bed late")
} catch {
  case e: JimOverslept => println(e)
}

输出:playground.CaseClassOutput$JimOverslept

实际上,我更喜欢JimOverslept(went to bed late)

这样的输出

两个输出如此不同的原因是什么?获得所需输出的最佳方法是什么 (JimOverslept(went to bed late))

根据SLS 5.3.2 Case Classes

Every case class implicitly overrides some method definitions of class scala.AnyRef unless a definition of the same method is already given in the case class itself or a concrete definition of the same method is given in some base class of the case class different from AnyRef.

现在 toString 已经由基础 class 在

中提供
case class JimOverslept(msg: String) extends Exception

其中 Exception 扩展基础 Throwable 提供 toString 定义。因此,请尝试在案例 class 本身内提供覆盖,例如

case class JimOverslept(msg: String) extends Exception {
  override def toString: String = scala.runtime.ScalaRunTime._toString(this)
}