//模式匹配
//定义一个普通类
class Student(n: String, a: Int) {
//定义一些成员变量
var name: String = n
var age: Int = a
}
//以下注释放开 普通类也可以使用样例类的方式使用模式匹配,样例类本身会帮我们自动实现这两个方法
伴生类
//object Student {
// def apply(n: String, a: Int): Student = new Student(n, a)
// apply方法有点类似于java中的构造函数,接受构造参数变成一个对象。那么unapply方法就刚好相反,他是接受一个对象,从对象中提取出相应的值
// def unapply(arg: Student): Option[(String, Int)] = {
// if (arg == null) None else Some(arg.name, arg.age)
// }
//}
//定义一个样例类 就一行 很简单
case class Teacher(name: String, age: Int)
//测试
object MatchDemo3 extends App {
//非样例类的模式匹配
//先声明对象
var student:Student=new Student("小王",19)
var student1:Student=new Student("小李",21)
def matchTest03(x: Student) = x match {
case x if x.age < 20 => println("young")
case x if x.age >= 20 => println("old")
}
matchTest03(student) //-->young
matchTest03(student1) //-->old
//样例类的模式匹配
//不用new声明对象
def matchTest04(x: Teacher) = x match {
case Teacher(name, age) if age < 30 => println("young")
case Teacher(name, age) if age >= 30 => println("old")
}
matchTest04(Teacher("王老师",29)) //-->young
matchTest04(Teacher("李老师",31)) //-->old
}
scala学习--普通类和样例类的模式匹配
最新推荐文章于 2022-07-29 20:04:37 发布