初次接触groovy

初次接触groovy,第1张

概述 项目算完成了,等测试报告出来的时间里玩玩groovy,不玩不知道,一玩吓一跳,groovy与ruby好象啊。 看看下面的代码: ruby : [ 1 , 2 , 3 , 4 , 5 , 6 , 7 ] . inject( 0 ){ | sum , i |  sum += i} groovy : [ 1 , 2 , 3 , 4 , 5 , 6 , 7 ] . inject( 0 ){sum , i  项目算完成了,等测试报告出来的时间里玩玩groovy,不玩不知道,一玩吓一跳,groovy与ruby好象啊。
看看下面的代码:

ruby :

[
1 , 2 , 3 , 4 , 5 , 6 , 7 ] . inject( 0 ){ | sum , i |  sum += i}

groovy :


[
1 , 7 ] . inject( 0 ){sum , ->  sum += i}

ruby的closures与groovy的closures机制几乎完全一样,除了符号改变之外。有兴趣的话看看这个:
http://groovy.codehaus.org/Tutorial+2+-+Code+as+data%2C+or+closures

如果说groovy有什么优点的话,就是它可以直接利用java丰富的类库,实在爽:

// readfile . groovy

myfilename 
=   " E://groovy//readfile.groovy "

myfile 
=  new file( myfilename)

printfileline 
=  { println  " file line:  "   +  it }

myfile
. eachline( printfileline )

语法层面没什么好谈的,我更希望了解下groovy在实际应用中的表现,IBM的develper works上面有个实战groovy系列,值的好好读读

补充下,在spring中调用groovy beans的方法:
首先需要一个java接口,比如:

package  com . sohu . blog . dennis_zane . springdemo . scripting;


public interface Calculator {

   
int  add( int  x , int  y);

}


然后是Groovy bean
:

// GroovyCalculator . groovy

package  com . sohu . blog . dennis_zane . springdemo . scripting;

class GroovyCalculator implements Calculator{

  
int  add( int  x ,   int  y){

      x
+ y    

  }

}


在spring配置文件中配置:

< lang : groovy ID = " calculator "  script - source = " classpath:/com/sohu/blog/dennis_zane/springdemo/scripting/GroovyCalculator.groovy " />

调用的话跟使用一般的bean没什么不同:

Calculator calculator = (Calculator)ctx . getBean( " calculator " );

System . out . println(calculator . add( 100 ,   20 ));

也许随着groovy性能的提升,将业务层完全由动态语言来实现不是没有可能。

总结

以上是内存溢出为你收集整理的初次接触groovy全部内容,希望文章能够帮你解决初次接触groovy所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1268972.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-08
下一篇 2022-06-08

发表评论

登录后才能评论

评论列表(0条)

保存