(一)case class的定义
case class 是 Scala 中一种特殊的类,它用于创建不可变的数据容器。
语法如下:
case class ClassName(parameter1: Type1, parameter2: Type2,...)
(二)case class的特点
(1)不可变性
case class 创建的对象是不可变的,一旦创建,其属性值不能被修改。
package caseclass
//Set对装入的对象进行去重
import scala.collection.mutable
object caseclass01 {
class Book(var id:Int,var name:String) {
override def equals(obj: Any): Boolean = {
val other = obj.asInstanceOf[Book]
other.id == id && other.name == name
}
override def hashCode(): Int = id
}
def main(args: Array[String]): Unit = {
val set1:mutable.Set[Int] = mutable.Set(1,2)
set1 += 1
set1 += 1
set1 += 1
set1 += 1
println(set1)
val book1 = new Book(1,"西游记")
val book2 = new Book(1,"西游记")
println(book1 == book2)
//定义一个set 它的类型是Book 他可以装入的数据是book类型
val set2 :mutable.Set[Book] = mutable.Set()
set2 += book1
set2 += book2
println(set2)
}
}
//运行结果:
HashSet(1, 2)
true
HashSet(caseclass.caseclass01$Book@1)
(2)实例化可以省略new
普通的class 在实例化时,必须要写new的。
(3)自动重写方法: toString, equals, hashCode, copy。
package caseclass
//Set对装入的对象进行去重
import scala.collection.mutable
object caseclass02 {
case class Book(var id: Int, var name: String) {
}
def main(args: Array[String]): Unit = {
val book1 = Book(1, "西游记")
val book2 = Book(1, "西游记")
println(book1 == book2)
//定义一个set 它的类型是Book 他可以装入的数据是book类型
val set2: mutable.Set[Book] = mutable.Set()
set2 += book1
set2 += book2
println(set2)
}
}
//运行结果;
true
HashSet(Book(1,西游记))
自动生成方法:
1.to String方法
当我们定义一个 case class 时,Scala 会自动生成toString方法,它会返回一个包含类名和参数值的字符串表示。
2.equals 和 hashCode 方法
equals和hashCode方法用于比较和哈希 case class 的实例。
val student1 = Student("Alice", 18, "Grade 12")
val student2 = Student("Alice", 18, "Grade 12")
println(student1.equals(student2))
// 输出:true
println(student1.hashCode == student2.hashCode)
// 输出:true
案例代码:
package caseclass
/*
* case class:样板类
*
* 1.可以省略new
* 2.属性默认是不可变的。val修饰
* 3.他会自动化去实现toString,equlas,hasCode等方法
* */
object caseclass03 {
case class Student(name: String, age: Int){
}
def main(args: Array[String]): Unit = {
//val st1 = new Student("小花",18)
//可以省略new
val st1 = Student("小花",18)
val st2 = Student("小花",18)
//属性默认是不可变的。val修饰
//st1.name="小花花"
println(st1)
println(st1 == st2)
}
}
//运行结果:
Student(小花,18)
true
3.copy方法
copy方法可以用于创建一个与原实例相似的新实例,我们可以选择性地修改某些参数。