![665cf79d2618cb2d654673b3fff95b80.png](https://i-blog.csdnimg.cn/blog_migrate/89fc2a9bc75281acfd4534eaa9dc15e7.jpeg)
大数据Scala系列之模式匹配和样例类
1.样例类
在Scala中样例类是一中特殊的类,样例类是不可变的,
可以通过值进行比较,可用于模式匹配。
定义一个样例类:
构造器中每一个参数都是val,除非显示地声明为var
伴生对象提供apply ,让你不使用new关键字就能构造出相应的对象
case class Point(x: Int, y: Int)
创建样例类对象:
val point = Point(1, 2)val anotherPoint = Point(1, 2)val yetAnotherPoint = Point(2, 2)//访问对象值
point.x
point.x =1 //不可以
通过值对样例类对象进行比较:
if (point == anotherPoint) {
println(point + " and " + anotherPoint + " are the same.")
} else {
println(point + " and " + anotherPoint + " are different.")
}// Point(1,2) 和 Point(1,2)一样的.if (point == yetAnotherPoint) {
println(point + " and " + yetAnotherPoint + " are the same.")
} else {
println(point + " and " + yetAnotherPoint + " are different.")
}// Point(1,2)和Point(2,2)是不同的.
样例类的拷贝
You can create a (shallow) copy of an instance of a case class simply by using the copy method. You can optionally change the constructor arguments.
case class Message(sender: String, recipient: String, body: String)val message4 = Message("julien@bretagne.fr", "travis@washington.us", "Me zo o komz gant ma amezeg")val message5 = message4.copy(sender = message4.recipient, recipient = "claire@bourgogne.fr")
message5.sender // travis@washington.us
message5.recipient // claire@bourgogne.fr
message5.body // "Me zo o komz gant ma amezeg"
在模式匹配中使用样例类:
abstract class Amount// 继承了普通类的两个样例类case class Dollar(v