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)


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值