Scala中继承的案例类的toString方法 [英] toString method for inherited case class in Scala
本文介绍了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)
)
推荐答案
查看全文