资源描述:
《why scala - ThoughtWorks - ZhanHonglai》由会员上传分享,免费在线阅读,更多相关内容在学术论文-天天文库。
1、WHYSCALA1CLEANCODE23为什么写不好代码?我赶时间我懒我不care什么是好代码?缺少资源我只喜欢做新东西4比写代码更难的是看别人的代码5JAVA开发库Google GuavaApache CommonsSpringGuiceScala !6WHYSCALA?简洁强大有趣!快速逐渐流行的趋势!7谁正在使用SCALA?8来看看PERSON类-JAVApublicclass Person {private String name;privateintage;!public Person(String name, int
2、age) {this.name = name;this.age = age;}public String getName() {returnname;}publicvoid setName(String name) {this.name = name;}publicint getAge() {returnage;}publicvoid setAge(int age) {this.age = age;}}9来看看PERSON类-SCALAcase class Person(name: String, age: Int)10似乎还少了
3、点什么 @Overridepublic String toString() {return String.format("Person: %s age: %s", name, age);}@Overridepublicint hashCode() {int hashCode = 0;for(char c: name.toCharArray()) {hashCode += c;}return 11 * hashCode + age; }@Overridepublicboolean equals(Object other) {if(o
4、ther == null) returnfalse;if(other instanceof Person) {Person person = (Person)other;return person.name.equals(name) && person.age == age;}returnfalse;}11是的,你没看错case class Person(name: String, age: Int)12测试valhonglai=newPerson("honglai",26)!honglai.toString!"Person(ho
5、nglai,26)"valanotherHonglai=newPerson("honglai",26)!honglaiequalsanotherHonglai!//trueMap(honglai->1,anotherHonglai->2).size!//113用SCALA来解释class Person(val name: String, val age: Int)object Person {def apply(name: String, age: Int) = new Person(name, age)// def hashCo
6、de(): Int// def toString(): String// def equals(other: Object): Booleandef unapply(p: Person): Option[(String, Int)]=Some(p.name, p.age) }14CASECLASSobjectapplyscala> val honglai = Person("honglai", 26) honglai: Person = Person(honglai,26)valscala> honglai.name = "zha
7、n" :10: error: reassignment to val honglai.name = "zhan" ^objectunapplyscala> honglai match {
8、 case Person(name, age) => name+ " 今年 " + age + "岁"
9、 case _ => "error"
10、 } res1: String = honglai 今年 26岁15类型匹配-JAVAObject
11、 x = new Person("Honglai", 34);if(x instanceof Person) {Person p = (Person)x;System.out.println("Person name: "+p.getName())