scala入门初级代码训练-28CaseClass的模式匹配应用

原创文章,转载请注明出处!

原文地址: http://www.ptbird.cn/2016/07/19/scala-chuji-demo-28/

There I am,in the world more exciting!

by postbird

www.ptbird.cn



package com.ptbird.scala

/**
* Created by postbird on 2016/5/26.
*/

abstract class Person2

case class Student(age: Int) extends Person2

//采用默认的 val 参数

case class Worker2(age: Int, salary: Double) extends Person2

case object Shared extends Person2

object CaseClassObject {
def main(args: Array[String]): Unit = {
def caseFunc(person: Person2) = person match {
case Student(age) => println(age + " years old")
case Worker2(age, salary) => println("salary " + salary)
case Shared => println("No property")
}

caseFunc(Student(10))
caseFunc(Worker2(12, 23.0))
caseFunc(Shared)
// 10 years old
// salary 23.0
// No property

val worker = new Worker2(23, 100.1)
val worker2 = worker.copy(salary = 100.2)
val worker3 = worker.copy(age = 30)

//copy的时候,即使是val,也可以改变age 的值

println(worker)
println(worker2)
println(worker3)
// Worker2(23,100.1)
// Worker2(23,100.2)
// Worker2(30,100.1)
}
}

欢迎评论。
lingkb » scala入门初级代码训练-28CaseClass的模式匹配应用

发表评论