scala中的caseclass

45 阅读1分钟

case class 是 Scala 中一种特殊的类,它用于创建不可变的数据容器


// 这里对scala的集合进行重写
import scala.collection.mutable

object CaseClass {
  class Book(var id: Int, var name: String) {
    override def equals(other: Any): Boolean = {
      val other = other.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)
  }
}

image.png


// 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)
  }
}

case class: 样板类

  1. 可以省略 new
  2. 属性默认是不可变的。val 修饰
  3. 它会自动去实现toString, equals, hasCode等方法 image.png
  case class Book(id:Int, name:String, author:String, price:Double, amount:Int)

  def main(args: Array[String]): Unit = {
    // 2
    val bookList: ListBuffer[Book] = ListBuffer()
    // 3
    val book1 = Book(1, "凡人修仙记", "梦语", 20.2, 1)
    val book2 = Book(2, "偏偏总裁爱上我", "梦语", 100, 1)
    val book3 = Book(3, "重生之超级神豪", "梦语", 50, 1)
    bookList += book1
    bookList += book2
    bookList += book3
    // 4
    bookList += Book(6, "新增书籍", "作者", 30.5, 2)
    // 7 删除id为1的书
    // val idx = 1
    // bookList.find
    bookList.remove(0)
    // 8 sortWith
    val newList = bookList.sortWith((a, b) => {
      a.price > b.price
    })
    // 9
    newList.foreach(ele => {
      println(s"${ele.id} ${ele.name} ${ele.price}")
    })
    // 10
    var totalPrice = 0.0
    newList.foreach(ele => {
      totalPrice += ele.price * ele.amount
    })
    println(s"总价格: $totalPrice")
  }
}

image.png