case class的定义
case class 是 Scala 中一种特殊的类,它用于创建不可变的数据容器。
语法如下:
case class ClassName(parameter1: Type1, parameter2: Type2,...)
Set对装入的对象去重
需补充的方法:
-
override def equals(obj: Any): Boolean = { val other = obj.asInstanceOf[Book] other.id == id && other.name == name }
-
override def hashCode(): Int = id }
package caseclass
//Set对装入的对象去重
import scala.collection.mutable
object caseclass1 {
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
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)
}
}
运行结果
使用caseclass简化:
package caseclass
//Set对装入的对象去重
import scala.collection.mutable
object caseclass2 {
case class Book(var id:Int, var name:String) {}
def main(args: Array[String]): Unit = {
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)
}
}
运行结果
case class: 样板类
- 可以省略 new
- 属性默认是不可变的。val 修饰
- 它会自动去实现toString, equals, hashCode等方法
package caseclass
// case class: 样板类
// 1. 可以省略 new
// 2. 属性默认是不可变的。val 修饰
// 3. 它会自动去实现toString, equals, hashCode等方法
object caseclass3 {
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)
}
}