15 使用lambdas和闭包
1 使用lambdas和闭包
1.1 定义闭包
闭包是一个代码块,代替了方法或类。
groovy中的闭包基于后边的构造方式:{list of parameters-> closure body}.其中,-> 之前的值为声明的闭包参数。
如果只有一个变量的时候,可以使用固有变量 it 。
如果没有返回值被定义,则返回-> 后边的值。it 的返回值的用法,参见下例子,
|
package closures class ClosuresTest { static main(args) { //返回input,使用固有的变量it def returnInput = {it}; assert "test" == returnInput("test"); //返回input,不使用固有的变量it def returnInput2 = {s->s}; assert "test" == returnInput2("test"); } } |
1.2 闭包中定义默认值
闭包中,也可以定义参数的默认值。
|
package closures class ClosuresDefaultValue { static main(args) { def multiply = {int a,int b=10 -> a*b; }; assert multiply(2) == 20; assert multiply(2,5) == 10 } } |
1.3 例子:each方法中使用闭包
在集合中使用闭包的例子,
|
package closures class ClosuresEach { static main(args) { List<Integer> list = [5,6,7,8]; println ("====自定义变量"); list.each {line -> print line+","; }; println ("\r\n====固有变量"); list.each ({ print it+","; }); println ("\r\n====计算从1到10的和"); def total = 0; (1..10).each { total += it; }; println total; } } |
1.4 例子:通过string的长度对list排序
|
package closures class ClosuresSort { static main(args) { def List strings = "this is a long sentence".split(); strings.sort{s1,s2 -> s1.size() <=> s2.size(); }; println strings; } } |
输出
|
[a, is, this, long, sentence] |
1.5 使用with方法
每个groovy对象都有一个with 方法,在该方法内,允许调用多个方法或属性,并将所设置的值或执行的方法都应用到该对象中。
|
package closures import java.util.List; class WithObj { String property1; String property2; List<String> list = []; def addElement(value) { list << value; }; def returnProperties() { "Property 1:$property1,Property 2:$property2"; } } |
|
package closures class ClosuresWithMethod { static main(args) { def sample = new WithObj(); def result = sample.with { property1="Input 1"; property2="This is cool"; addElement("Ubuntu"); addElement("Android"); addElement("Linux"); returnProperties(); }; println result; assert 3==sample.list.size(); assert "Input 1" == sample.property1; assert "This is cool" == sample.property2; assert "Linux" == sample.list[2]; def sb = new StringBuilder(); sb.with { append("this "); append("is "); append("appended"); }; println sb; } } |
输出:
|
Property 1:Input 1,Property 2:This is cool this is appended |
15 使用lambdas和闭包的更多相关文章
- 15 python 初学(闭包,函数装饰器)
这一部分很重要,一定要透彻理解.可参考大神博客: http://www.cnblogs.com/yuanchenqi/articles/5830025.html 闭包: 如果在一个内部函数里,对在外 ...
- Python入门笔记(22):Python函数(5):变量作用域与闭包
一.全局变量与局部变量 一个模块中,最高级别的变量有全局作用域. 全局变量一个特征就是:除非被删除,否则他们存活到脚本运行结束,且对于所有的函数都可访问. 当搜索一个标识符(也称变量.名字等),Pyt ...
- Groovy闭包
定义 闭包(Closure)是一种数据类型,它代表一段可执行的代码.它可以作为方法的参数,或者返回值,也可以独立运行,定义如下: def xxx = {parameters -> code} ...
- Swift5 语言指南(九) 闭包
闭包是自包含的功能块,可以在代码中传递和使用.Swift中的闭包类似于C和Objective-C中的块以及其他编程语言中的lambdas. 闭包可以从定义它们的上下文中捕获和存储对任何常量和变量的引用 ...
- 016.Python闭包函数以及locals和globals
一 闭包函数 内函数使用了外函数的局部变量,并且外函数把内函数返回出来的过程叫做闭包,这个内函数叫做闭包函数 1.1 闭包函数语法 def outer(): a = 5 def inner(): pr ...
- 我的游戏蜗牛web前端面试经历
蜗牛在江苏苏州地区应该算是比较大的互联网公司了,可以称得上中国游戏的鼻祖,之前一直很想进蜗牛,但作为一个应届毕业生却没有看到蜗牛发布任何关于招聘实习生的职位,无奈之下于是就毛遂自荐了,主动以邮件的形式 ...
- 自学Python二 Python中的屠龙刀(续)
函数 秉承着一切皆对象的理念,函数作为对象,可以为其赋值新的对象名,也可以作为参数传递给其他函数! 正常的诸如空函数,默认参数等等我们就不提了,在这里着重提一下默认参数里面的坑和lambda函数. 当 ...
- PHP5.3, PHP5.4, PHP5.5新特性
PHP 5.3中的新特性 1. 支持命名空间 (Namespace) 2. 支持延迟静态绑定(Late Static Binding) 3. 支持goto语句 4. 支持闭包.Lambda/Anony ...
- 前端面试题第一波,要offer的看过来~
一.HTML常见题目 01.Doctype作用?严格模式与混杂模式如何区分?它们有何意义? 02.HTML5为什么只需要写<!DOCTYPE HTML>? 03.行内元素有哪些?块级元素有 ...
随机推荐
- Good Bye 2015 B. New Year and Old Property —— dfs 数学
题目链接:http://codeforces.com/problemset/problem/611/B B. New Year and Old Property time limit per test ...
- 动态inventory脚本的python实现
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' 基于python的动态inventory脚本实例 ''' import os import sys ...
- hadoop集群异常问题总结
1. Could not find or load main class java.library.path=.opt.hadoop.lib 我的环境上是 hadoopopts变量的配置问题,至于为啥 ...
- tomcat正常启动,但是java项目没有启动原因
右键项目,选择properties,查看该属性配置的是否正确
- NSMutableURLRequest,在POST方式下传递参数
1. [代码][C/C++]代码 NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; NSUs ...
- BluetoothLE-Multi-Library
github地址:https://github.com/qindachang/BluetoothLE-Multi-Library BluetoothLE-Multi-Library 一个能够连接多台蓝 ...
- bzoj 1086 [SCOI2005]王室联邦——思路
题目:https://www.lydsy.com/JudgeOnline/problem.php?id=1086 于是去看了题解. 要回溯的时候再把自己加进栈里判断.这样才能保证剩下的可以通过自己连到 ...
- Java编程环境eclipse配置
一. 下载并安装JDK https://www.cnblogs.com/zhangchao0515/p/6806408.html 二.下载并解压Eclipse https://www.cnblogs. ...
- CF-798A
A. Mike and palindrome time limit per test 2 seconds memory limit per test 256 megabytes input stand ...
- c/c++面试30-38之指针
30 看代码写结果-----指针加减 #include <stdio.h> int main(void) { ] = { , , , , }; );//这里要特别注意,&a+1的值 ...