`
xnnyygn
  • 浏览: 42810 次
  • 性别: Icon_minigender_1
  • 来自: 上海
最近访客 更多访客>>
社区版块
存档分类
最新评论

groovy in action 笔记 2

阅读更多
这里看的时间稍微长了一点,从43到100页,看起来还算顺。

首先是看到一个spaceship operator: <=>,作为少数dynamic language拥有的特殊比较符号,可以认为是以下函数
//a<=>b
if(a>b){return 1;}
else if(a==b){return 0;}
else if(a<b){return -1}
else {return undef;}


第二个是duck typing。xy并没有完全理解这个词组的意思,按照WIKIPEDIA的解释:

duck typing is a style of dynamic typing in which an object's current set of methods and properties determines the valid semantics, rather than its inheritance from a particular class or implementation of a specific interface.

而duck typing的由来是duck testing,也就是“某个学鸭子走路,鸭子叫的鸟,我们认为是鸭子”的实验。

就XY的理解,方法体 a*3, 假如a是int,则返回数学意义上的乘法,但是如果我输入‘hello',则返回'hellohellohello',也就是连接起来的3个'hello'。有人认为这种方法需要写文档,提示programmers。

另外一方面,这个duck typing是static 和dynamic language的不同的地方,作为从static过渡到dynamic的,需要学习这个duck typing来发挥dynamic的优势。

第三个是double dispatch,WIKIPEDIA的解释:
double dispatch is a mechanism that dispatches a function call to different concrete functions depending on the runtime types of multiple objects involved in the call.

XY的理解基于1+1.0,按照dynamic language的设定,这个1是Integer,而这个1.0是BigDecimal,假如我在Integer的类中写上plus(BigDecimal ???)的语句的话,我可以调用BigDecimal的plus(Integer ???)的方法。事实上1+1.0==1.0+1,而我确实可以通过这个double dispatch来reuse。不过个人认为这样做有一个前提,就是parameters必须是object,否则double dispatch会有限制。这个问题在dynamic language上基本不会出现。

第四个是1+1的问题,也就是类型问题,因为java中除了String之外,Object和Object不能相加,只有primitive类型才可以操作。但是在dynamic language中,这个限制被取消了,这里的两个1都是Integer,调用plus方法,返回一个值为2的Integer。

虽然这个1+1问题是在autoboxing的时候提到的,但是,只要不接触java代码,那么就没有autoboxing的步骤。

最后是让xy可能一生难忘的“一行遍历当前目录下所有文件/文件夹“的代码。
new File('.).eachFileRecurse{println it}


这句话中有很多可以分析的要点。
1:'',这个是单引号,而不是双引号。按照groovy的设定,单引号内容不解析,这个是需要了解的。
2:new File('.'),匿名类的实例+构造函数,这个和java区别不大。
3:eachFileRecurse,递归遍历文件,可以附加一个closure
4:{println it}:,losure,默认的参数为it,这个要记住
5:println it,it为一个java.io.File的实例,知道这个之后我们可以把it替换为it.size()来遍历显示文件大小(包括文件夹);其次println调用了it的toString()方法。

结语:再次被dynamic language的魅力征服
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics