Scala学习笔记(二)Case的作用

这次主要是为了理解Case Class,习惯了Java的编程方式,会觉得Case Class这种写法有一点怪怪的。看看官方的解释是什么吧:

Case classes and case objects are defined like a normal classes or objects, except that the definitions is prefixed with the modifier case.
1. Case classes implicitly come with a constructor function, with the same name as the class.
2. Case classes and case objects implicitly come with implementations of methods toString, equals and hashCode, which override the methods with the same name in class AnyRef.
3. Case classes implicitly come with nullary accessor methods which retrieve the constructor agruments
4. Case classes allow the constructions of patterns which refer to the case class constructor

 

其实翻译过来按照笔者的理解Case Class只是在Class的声明前面添加了Case这个标记符,从而让编译器识别出来然后帮助完成一些类似JavaBean风格的冗余代码。比如依照Class的声明添加了合适的构造函数,重写了toString、equals等方法,并在生成Java代码的时候,优雅的生成了符合JavaBean规范的getter/setter。另外在使用这样的Class构造实例的时候,可以利用pattern matching省去new这样的关键字。

 

举个简单的例子:(其实getter和setter的自动添加还可以通过@BeanProperty这个Annotation来实现)

case class Person(firstName: String, lastName: String)
 
val me = Person("Daniel", "Jin")
val firstN = me.firstName
val lastN = me.lastName
 
println(me == Person(first, last))
println(me)


 

你可能感兴趣的:(Scala学习笔记(二)Case的作用)