上面的理解是http://www.aboutyun.com/thread-23464-1-1.html
下面代码原创是https://blog.csdn.net/yyywyr/article/details/50300303
case class 跟普通class有什么区别 1、初始化的时候,不需要new,当然你也可以加上,普通类一定需要加上new 2、toString的实现更加漂亮 3、默认实现了equals hashcode 4、默认是可以序列化的,也就是实现了Serializable 5、自动从scala.Producet中继承了一些函数 6、case class构造函数的参数是publiec级别的,我们可以直接访问 7、支持模式匹配 上面其实我们已经明白了case class ,其实就是class,与其它class有所不同。 1、代码示例
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
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、结果
1
yy is a student,sno is
:
20151214
注意,当一个类被生成为case class 时,scala会默认作如下工作: (1)如果参数不加var/val修改,默认为val。 (2)自动创建伴生对象,实现apply方法,方便了我们在创建对象时不适用new (3)实现自己的toString、hashCode、copy和equals方法 3、copy等方法介绍
01
02
03
04
05
06
07
08
09
10
11
12
13
14
val
t
=
Teacher(
"xx"
,
2015
)
println(
"toString:"
+ t.toString())
println(
"hashCode:"
+ t.hashCode())
//深度copy
val
t
1
=
t.copy()
println(
"copy之无参拷贝:"
+ t
1
)
println(
"copy之无参拷贝t内容是否equals t1:"
+ t.equals(t
1
))
println(t
==
t
1
)
val
t
2
=
t.copy(name
=
"zz"
)
println(
"t2:"
+ t
2
.toString())
val
t
3
=
t.copy(tno
=
111
)
println(
"t3:"
+ t
3
)
val
t
4
=
t.copy(
"ww"
,
222
)
println(
"t4:"
+ t
4
)
结果如下:
1
2
3
4
5
6
7
8
toString
:
Teacher(xx,
2015
)
hashCode
:
-
1236856524
copy之无参拷贝
:
Teacher(xx,
2015
)
copy之无参拷贝t内容是否equals t
1
:
true
true
t
2
:
Teacher(zz,
2015
)
t
3
:
Teacher(xx,
111
)
t
4
:
Teacher(ww,
222
)
4、多个参数的case class
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
package
com.yy.base
/**
* case class 多个参数示例
*/
abstract
class
Person
1
case
class
Student
1
(name
:
String,sno
:
Int)
extends
Person
1
case
class
Teacher
1
(name
:
String,tno
:
Int)
extends
Person
1
case
class
None
1
(name
:
String)
extends
Person
1
//SchoolPerson包含0或者多个Person类型参数的类
case
class
SchoolPerson(desc
:
String, person
:
Person
1
*)
object
CaseClassNestedTest
extends
App {
val
sp
=
SchoolPerson(
"多个Person类型的类"
,Student
1
(
"xx"
,
11
),Teacher
1
(
"yy"
,
22
))
sp
match
{
case
SchoolPerson(
_
,Student
1
(name,sno),
_
)
=
> println(name+
":"
+sno)
case
SchoolPerson(
_
,
_
,Teacher
1
(name,tno))
=
> println(name+
":"
+tno)
case
_
=
> println(
"NO"
)
}
}
结果为