比较
case class vs class
1.toString equals hashcode 重写
2.不用 new
3.默认实现了序列化接口
case class vs case object
1.case class 修饰的类,必须要有参数列表
2.case object 修饰的对象,必须不能有参数列表
package com.fun.scala
object Person {
def apply () ={
println("apply object person")
new Person
}
def main(args: Array[String]): Unit = {
Person().test()
// new Class
val person = new Person
// com.fun.scala.Person@35bbe5e8
println(person)
// class person apply
println(person())
}
}
class Person() {
def apply() = {
"class person apply"
}
def test(): Unit ={
println("class test")
}
}
结果如下:
package com.fun.scala
object ExampleCase {
}
case object Person {
def main(args: Array[String]): Unit = {
val p1 = new PersonEx("test", 11)
val p2 = new PersonEx("test", 11)
// p1==p2 值 false
println(s"p1==p2 值 ${p1==p2}")
println(p1)
val d1 = Dog("旺财")
val d2 = Dog("p")
// d1==d2 值 true
println(s"d1==d2 值 ${d1==d2}")
// Dog(旺财)
println(d1)
}
}
case class Dog(name: String)
class PersonEx(name: String, age: Int) {
}
结果如下图:
scala 伴生对象、伴生类、case class、case object 至此结束。