美文网首页安卓开发博客
android gradle closure闭包

android gradle closure闭包

作者: 黑色海鸥 | 来源:发表于2018-07-23 23:21 被阅读5次

参考

https://blog.csdn.net/innost/article/details/48228651

定义

一种数据类型,它代表了一段可执行的代码;是可以将函数作为参数传递和使用,有点回调函数的感觉;

代码形式

  • 标准形式

def aClosure= {//闭包是一段代码,所以需要用花括号括起来..
    String param1, int param2 ->  //这个箭头很关键。箭头前面是参数定义,箭头后面是代码
    println"this is code" //这是代码,最后一句是返回值,
   //也可以使用return,和Groovy中普通函数一样

  • 简化形式
def xxx = {paramters -> code}  //或者  
def xxx = {无参数,纯code}  这种case不需要->符号
  • 隐藏参数形式
    闭包没定义参数的话,则隐含有一个参数,这个参数名字叫it,和this的作用类似。it代表闭包的参数。
//比如:
def greeting = { "Hello, $it!" }
assert greeting('Patrick') == 'Hello, Patrick!'
等同于:
def greeting = { it -> "Hello, $it!"}
assert greeting('Patrick') == 'Hello, Patrick!'
  • 无参数形式
    在闭包定义时,采用下面这种写法,则表示闭包没有参数!
def noParamClosure = { -> true }
这个时候,我们就不能给noParamClosure传参数了!
noParamClosure ("test")  <==报错喔!
  • 调用形式
    闭包对象.call(参数)
    or
    闭包对象(参数)
// 比如
aClosure.call("this is string",100)  或者
aClosure("this is string", 100)

Closure使用中的注意点

  • 省略圆括号

在Groovy中很多类都定义了一些函数,这些函数最后一个参数是一个闭包的时候,可以省略函数的花括号;

//例子一:
public static <T> List<T>each(List<T> self, Closure closure)
// 上面这个函数表示针对List的每一个元素都会调用closure做一些处理。
// 这里的closure,就有点回调函数的感觉。但是,在使用这个each函数的时候,我们传递一个怎样的Closure进去呢?请看下面
def iamList = [1,2,3,4,5]  //定义一个List
iamList.each{ //调用它的each,这段代码的格式看不懂了吧?each是个函数,圆括号去哪了?
      println it
}
//例子二:
def testClosure(int a1,String b1, Closure closure){
      //dosomething
     closure() //调用闭包
}
testClosure 4, "test", {
     println"i am in closure"
} 

  • 确定Closure的参数
    只能通过查询API文档才能了解上下文语义。多查api文档

相关文章

  • android gradle closure闭包

    参考 https://blog.csdn.net/innost/article/details/48228651 ...

  • 关于rust中的闭包(一)

    闭包 在计算机中,闭包 Closure, 又称词法闭包 Lexical Closure 或函数闭包 functio...

  • 关于闭包

    闭包的英文是closure,又称词法闭包(Lexical Closure)和函数闭包(Function Closu...

  • 理解闭包

    闭包 何为闭包 闭包(Closure)是词法闭包(Lexical Closure)的缩写 高级程序设计中写有权访问...

  • python之闭包与装饰器

    1 闭包 维基百科给出的解析:闭包(英语:Closure),又称词法闭包(Lexical Closure)或函数闭...

  • 闭包,定时器

    问题 1.什么是闭包? 有什么作用 闭包(英语:Closure),又称词法闭包(Lexical Closure)或...

  • [Code] 优雅地使用python闭包

    在计算机科学中,闭包(英语:Closure),又称词法闭包(Lexical Closure)或函数闭包(funct...

  • golang:函数闭包

    From wiki 闭包在计算机科学中,闭包(英语:Closure),又称词法闭包(Lexical Closure...

  • 理解Python闭包

    1.什么是闭包? 维基百科: 在计算机科学中,闭包(Closure)是词法闭包(Lexical Closure)的...

  • Swift底层进阶--011:闭包

    什么是闭包 维基百科中的解释:在计算机科学中,闭包(Closure),又称词法闭包(Lexical Closure...

网友评论

    本文标题:android gradle closure闭包

    本文链接:https://www.haomeiwen.com/subject/jqjsmftx.html