原创转载请注明出处:http://agilestyle.iteye.com/blog/2333708
创建一个case类时会自动创建toString方法,并且nice输出
创建一个非Case类时也会自动创建toString方法,但是ugly输出为对象在JVM中的内存的HashCode
要得到更有用的结果,就得override自己的toString方法
package org.fool.scala.strings
case class Teacher(name: String)
class Student(val age: Int)
class Student2(val age: Int) {
override def toString: String = s"Student is $age years old"
}
object ToStringTest extends App {
val teacher = Teacher("SB")
// Teacher(SB)
println(teacher)
val student = new Student(18)
// org.fool.scala.strings.Student@6bf256fa
println(student)
// Student is 30 years old
val student2 = new Student2(30)
println(student2)
}
Console Output

Scala中toString方法详解
本文通过实例介绍了Scala中case类和普通类的toString方法的区别。对于case类,默认情况下会生成一个友好的字符串表示形式;而对于普通类,默认的toString输出则是对象在JVM中的内存地址的HashCode。为了获取更实用的信息,可以通过覆写toString方法来自定义输出。
1230

被折叠的 条评论
为什么被折叠?



