Groovy的闭包示例

  1.  源代码:
  2. package mars.groovy
  3. /**
  4.  * @author Eric Han
  5.  * 2008-9-3 11:58:28
  6.  */
  7. public class MyClosure{
  8.  public static void main(def args){
  9.   def myfirstClosure={man->println "Hello ${man}"}
  10.   
  11.   myfirstClosure.call('Eric')
  12.   myfirstClosure('Carry')
  13.   
  14.   println ''
  15.   def map=['Eric':30,'bobo':29,'Carry':25]
  16.   map.each{println "${it.key} age is: ${it.value}"}
  17.   
  18.   println ''
  19.   map.findAll{age->age.value>28}.each{println it}
  20.   
  21.   println ''
  22.   def isAnyOneTrue=[11,12,13,14].any{n->n>12}
  23.   def isEveryOneTrue=[11,14].any{n->n>10}
  24.   println "any one is true? ${isAnyOneTrue}"
  25.   println "every one is true? ${isEveryOneTrue}"
  26.    
  27.   def result
  28.   println ''
  29.   def list=[1,2,3,4,5]
  30.   result=list.collect{n->return n*n}
  31.   println "collect result:${result}"
  32.   
  33.   println ''
  34.   def list1=[1,5]
  35.   result=list1.inject(1){previousValue,currentValue->previousValue*currentValue}
  36.   println "inject result:${result}"
  37.  }
  38. }
  39. 输出:
  40. Hello Eric
  41. Hello Carry
  42. Eric age is: 30
  43. bobo age is: 29
  44. Carry age is: 25
  45. bobo=29
  46. Eric=30
  47. any one is truetrue
  48. every one is truetrue
  49. collect result:[1, 4, 9, 16, 25]
  50. inject result:120

相关文章

背景:    8月29日,凌晨4点左右,某服务告警,其中一个...
https://support.smartbear.comeadyapi/docs/soapui/steps/g...
有几个选项可用于执行自定义JMeter脚本并扩展基线JMeter功能...
Scala和Java为静态语言,Groovy为动态语言Scala:函数式编程,...
出处:https://www.jianshu.com/p/ce6f8a1f66f4一、一些内部...
在运行groovy的junit方法时,报了这个错误:java.lang.Excep...