前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Groovy-10.闭包

Groovy-10.闭包

作者头像
悠扬前奏
发布2019-06-02 12:56:41
3910
发布2019-06-02 12:56:41
举报
文章被收录于专栏:悠扬前奏的博客
  • 闭包是一个短的匿名代码块,它表示一个函数,读取其他函数内部变量。
  • Groovy 用大括号定义闭包
代码语言:javascript
复制
class Example {
   static void main(String[] args) {
      def clos = {println "Hello World"};
      clos.call();
   } 
}
闭包中的形参

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

代码语言:javascript
复制
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");
   } 
}
在方法中使用闭包

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

代码语言:javascript
复制
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方法可以接受闭包作为参数,并将闭包应用于每一个元素。

代码语言:javascript
复制
class Example {
   static void main(String[] args) {
      def lst = [11, 12, 13, 14];
      lst.each {println it}
   } 
}
闭包和Map

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

代码语言:javascript
复制
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}"}
   } 
}
筛选

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

代码语言:javascript
复制
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)

迭代使用闭包作为转换器将每个元素转换为新的值

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018.05.14 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 闭包中的形参
  • 在方法中使用闭包
  • 集合和字符串中的闭包
    • 闭包和列表List
      • 闭包和Map
        • 筛选
        • 闭包的方法
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档