用Case类生成模板代码

将类定义为case类会生成许多模板代码,好处在于:

①会生成一个apply方法,这样就可以不用new关键字创建新的实例。

②由于case类的构造函数参数默认是val,那么构造函数参数会自动生成访问方法。如果是var也会有修改方法。

③会生成一个默认的toString的方法。

④会生成一个unapplay方法,在模式匹配时很好用。

⑤会生成equals和hashCode的方法。

⑥会生成copy的方法。

举个栗子:

①定义case时,在也不用new关键字来创建实例了:

scala> case class Person(name: String,relation: String)
defined class Person scala> val emily = Person("Joker","niece")
emily: Person = Person(Joker,niece)

②case类的构造函数人数默认的是val,所以会自动生成访问方法,但不会有修改的方法。

scala> case class Person(name: String,relation: String)
defined class Person scala> val emily = Person("Joker","niece")
emily: Person = Person(Joker,niece) scala> emily.name
res1: String = Joker scala> emily.name = "Marray"
<console>:14: error: reassignment to val
emily.name = "Marray"

③把case类的构造函数参数声明为var,既有修改方法又有访问的方法。

scala> case class Company(var name: String)
defined class Company scala> val a = Company("beijing shuma gs")
a: Company = Company(beijing shuma gs) scala> a.name
res2: String = beijing shuma gs scala> a.name = "shanghai jixie gs"
a.name: String = shanghai jixie gs

④case类的toString的方法的实现。

scala> case class Company(var name: String)
defined class Company scala> val a = Company("beijing shuma gs")
a: Company = Company(beijing shuma gs) scala> a
res3: Company = Company(beijing shuma gs)

⑤case class会自动生成一个unapply的方法,当需要在匹配表达式中提取信息时会很好用。

scala> case class Animal(name:String,age: Int)
defined class Animal scala> val a = Animal("Dog",10)
a: Animal = Animal(Dog,10) scala> a match {
| case Animal(n,m) => println(n,m)
| }
(Dog,10)

⑥case也同时生成了equals和hashCode,这样实例就可以比较了。

scala> case class Animal(name:String,age: Int)
defined class Animal scala> val a = Animal("Dog",10)
a: Animal = Animal(Dog,10) scala> val b = Animal("Pig",10)
b: Animal = Animal(Pig,10) scala> a ==b
res5: Boolean = false scala> val b = Animal("Dog",10)
b: Animal = Animal(Dog,10) scala> a==b
res6: Boolean = true scala> a.hashCode
res7: Int = -24782408

⑦case类创建一个copy方法,但需要克隆一个对象时很有用,在克隆时可以修改某些字段。

scala> case class Animal(name:String,age: Int,sex: String)
defined class Animal scala> val a = Animal("Dog",10,"nan")
a: Animal = Animal(Dog,10,nan) scala> val b = a.copy()
b: Animal = Animal(Dog,10,nan)
scala>
scala> val c = a.copy(name="Pig",sex="nv")
c: Animal = Animal(Pig,10,nv)
上一篇:java基本数据类型转换溢出问题


下一篇:Android studio 1.x 安装完毕后无法打开问题解决方案