原创转载请注明出处: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