Scala Case Class介绍

燕雨石
2023-12-01

1、代码示例

package com.yy.base

/**
 * case class 示例
 */
abstract class Person
case class Student(name:String,sno:Int) extends Person
case class Teacher(name:String,tno:Int) extends Person
case class None(name:String) extends Person

object CaseClassTest extends App {
    def caseClassMatch(p:Person) = p match{
      case Student(name,sno) => println(name + " is a student,sno is:" + sno)
      case Teacher(name,tno) => println(name + " is a teacher,tno is:" + tno)
      case None(name) => println("None matched")
    }
    
    val p = Student("yy",20151214)
    caseClassMatch(p)
}
2、结果

yy is a student,sno is:20151214
注意,当一个类被生成为case class 时,scala会默认作如下工作:

(1)如果参数不加var/val修改,默认为val。

(2)自动创建伴生对象,实现apply方法,方便了我们在创建对象时不适用new

(3)实现自己的toString、hashCode、copy和equals方法

3、copy等方法介绍

  val t = Teacher("xx",2015)
    println("toString:" + t.toString())
    println("hashCode:" + t.hashCode())
    //深度copy
    val t1 = t.copy()
    println("copy之无参拷贝:" + t1)
    println("copy之无参拷贝t内容是否equals t1:" + t.equals(t1))
    println(t==t1)
    val t2 = t.copy(name="zz")
    println("t2:" + t2.toString())
    val t3 = t.copy(tno=111)
    println("t3:" + t3)
    val t4 = t.copy("ww",222)
    println("t4:" + t4)
结果如下:

toString:Teacher(xx,2015)
hashCode:-1236856524
copy之无参拷贝:Teacher(xx,2015)
copy之无参拷贝t内容是否equals t1:true
true
t2:Teacher(zz,2015)
t3:Teacher(xx,111)
t4:Teacher(ww,222)

4、多个参数的case class

package com.yy.base

/**
 * case class 多个参数示例
 */
abstract class Person1
case class Student1(name:String,sno:Int) extends Person1
case class Teacher1(name:String,tno:Int) extends Person1
case class None1(name:String) extends Person1
//SchoolPerson包含0或者多个Person类型参数的类
case class SchoolPerson(desc:String, person:Person1*)

object CaseClassNestedTest extends App {
    val sp = SchoolPerson("多个Person类型的类",Student1("xx",11),Teacher1("yy",22))
    sp match{
      case SchoolPerson(_,Student1(name,sno),_) => println(name+":"+sno)
      case SchoolPerson(_,_,Teacher1(name,tno)) => println(name+":"+tno)
      case _ => println("NO")
    }
}
结果为

xx:11

 类似资料: