Groovy-10.闭包

  • 闭包是一个短的匿名代码块,它表示一个函数,读取其他函数内部变量。
  • Groovy 用大括号定义闭包
class Example {
   static void main(String[] args) {
      def clos = {println "Hello World"};
      clos.call();
   } 
}

闭包中的形参

闭包可以在定义闭包时引用变量,可以接受变量和参数:

class Example {     
   static void main(String[] args) {
      def str1 = "Hello";
      def clos = {param -> println "${str1} ${param}"}
      clos.call("World");
        
      // We are now changing the value of the String str1 which is referenced in the closure
      str1 = "Welcome";
      clos.call("World");
   } 
}

在方法中使用闭包

闭包可以作为方法的参数。

class Example { 
   def static Display(clo) {
      // This time the $param parameter gets replaced by the string "Inner"         
      clo.call("Inner");
   } 
    
   static void main(String[] args) {
      def str1 = "Hello";
      def clos = { param -> println "${str1} ${param}" }
      clos.call("World"); // Hello World 
        
      // We are now changing the value of the String str1 which is referenced in  Z      str1 = "Welcome";
      clos.call("World"); // Welcome World 
        
      // Passing our closure to a method
      Example.Display(clos); //Welcome Inner
   } 
}

集合和字符串中的闭包

List,Map,String有方法可以接受闭包作为参数。

闭包和列表List

列表的each方法可以接受闭包作为参数,并将闭包应用于每一个元素。

class Example {
   static void main(String[] args) {
      def lst = [11, 12, 13, 14];
      lst.each {println it}
   } 
}
闭包和Map

Mao的each方法可以接受闭包作为参数,并将闭包应用于每一个元素。

class Example {
   static void main(String[] args) {
      def mp = ["TopicName" : "Maps", "TopicDescription" : "Methods in Maps"]             
      mp.each {println it}
      mp.each {println "${it.key} maps to: ${it.value}"}
   } 
}
筛选

通过闭包可以很方便的使用闭包中的条件语句对元素进行筛选。

class Example {
   static void main(String[] args) {
      def lst = [1,2,3,4];
      lst.each {println it}
      println("The list will only display those numbers which are divisible by 2")
      lst.each{num -> if(num % 2 == 0) println num}
   } 
}

闭包的方法

闭包本身提供了一些方法:

方法 描述
Object find(Closure closure) 找到集合中与条件匹配的第一个值
List findAll(Closure closure) 找到对象中与条件匹配的所有值
boolean any(Closure closure)
boolean every(Closure closure)
方法any迭代集合的每个元素,检查布尔谓词是否对至少一个元素有效。
方法every检查是否对每一个元素有效
List collect(Closure closure) 迭代使用闭包作为转换器将每个元素转换为新的值
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 本章将会介绍 闭包表达式尾随闭包值捕获闭包是引用类型逃逸闭包自动闭包枚举语法使用Switch语句匹配枚举值关联值原...
    寒桥阅读 1,628评论 0 3
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,544评论 19 139
  • 天刚蒙蒙亮,我就兴奋地前往了杭州萧山机场,开启了香港之旅的首篇。我们大约是十点钟就抵达了香港,在一阵颠簸中,我看...
    落空de星辰阅读 472评论 1 3
  • 使用不需要上网单独下载jar包,只需要在配置文件pom.xml中配置jar包的依赖关系,就可以自动的下载jar包到...
    帷幄庸者阅读 412评论 1 0
  • 如果一张纸上画了一个圆圈,但是有一个缺口。那么当你扫见这个圆圈时,你会把注意力放在哪里呢,相信大多数人都会说,那个...
    绽蕊向阳阅读 250评论 1 2

友情链接更多精彩内容