39.scala编程思想笔记——自动字符串转换
欢迎转载,转载请标明出处:http://blog.youkuaiyun.com/notbaron/article/details/50447583
源码下载连接请见第一篇笔记。
Case类可以将对象连同其参数恰当的格式化为适于显示的形式,例如:
import com.atomicscala.AtomicTest._
case class Bicycle(riders:Int)
val forTwo = Bicycle(2)
forTwo is "Bicycle(2)" // Nice
在创建case类时,会自动创建称为toString的方法。无论何时,只要对某个对象进行操作,并希望是一个String,那么scala就会通过调用toString方法默默地为该对象产生一个String表示。
如果使用常规的非case类,那么需要定义自己的toString,如下:
import com.atomicscala.AtomicTest._
class Surrey2(val adornment:String) {
override deftoString =
s"Surrey with the $adornment"
}
val fancy2 = new Surrey2("fringe on top")
fancy2 is "Surrey with the fringe on top"
其中关键字override是Scala坚持使用的。因为toString已经定义过了。
良好的toString在调试程序时非常有用,有时只需看一眼对象的内部就知道发生了什么错误。