Scala中继承的案例类的toString方法 [英] toString method for inherited case class in Scala

查看:181
本文介绍了Scala中继承的案例类的toString方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Scala中为案例类调用toString方法时,我遇到了一些不一致之处.第一个代码示例:

I am facing some inconsistency in calling toString method for case-classes in Scala. The first code sample:

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

输出:Person(jim,42)

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

For the next code sample I used a case class that extends Exception:

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)

Actually, I would prefer the output like JimOverslept(went to bed late)

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

What is the reason the both outputs are so different? And what is the best way to obtain the output looks like desired one (JimOverslept(went to bed late))

推荐答案

根据

每个案例类都隐式重写该类的某些方法定义 scala.AnyRef 除非已给出相同方法的定义 在案例类本身或相同方法的具体定义中 是在案例类的某些基类中给出的,与A​​nyRef不同.

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已经由基类提供了

case class JimOverslept(msg: String) extends Exception

其中,Exception扩展了提供toString定义的基础Throwable.因此,尝试像这样在case类本身中提供覆盖.

where Exception extends base Throwable which provides toString definition. Hence try providing an override within the case class itself like so

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

这篇关于Scala中继承的案例类的toString方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆