迷人的case class带你沉迷未知空间☆*: .。. o(≧▽≦)o .。.:*☆

9 阅读1分钟

案例1:

Set 对装入的对象进行去重

package listANDcaseclass
import scala.collection.mutable

object caseclass1{
  class Book(val 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)
    val set2:mutable.Set[Book]=mutable.Set()
    set2 += book1
    set2 += book2
    println(set2)
  }
}

案例2:

package listANDcaseclass

import scala.collection.mutable

object caseclass2{
  case class Book(val id: Int, var name: String) {}
  def main(args: Array[String]): Unit = {

    val book1 = new Book(1,"西游记")
    println(book1)
    val book2 = new Book(1,"西游记")
    println(book2)
    val set2:mutable.Set[Book]=mutable.Set()
    set2 += book1
    set2 += book2
    println(set2)
  }
}

case class :样板类

  1. 可以省略 new

2.默认属性是不可变的,val 修饰

3.他会自己去实现toString ,equlas,hasCode等方法

package listANDcaseclass

import scala.collection.mutable

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)
    println(st1)
    println( st1 == st2)
  }
}