当前位置:网站首页>Closure of groovy
Closure of groovy
2022-06-22 14:37:00 【Leisurely summer】
1、 Introduce
Closure (Closure) Is a very important concept in many programming languages , that Groovy What is a closure in , The official definition is “Groovy Closure in is an open , Anonymous code block , Parameters... Are acceptable , Returns a value and assigns it to a variable ”, In short , He said an anonymous code block , Parameters... Are acceptable , There is a return value ,
2、 Closure Syntax
{ Parameter type Variable name -> Execute statement } If there is no parameter , I could just write it as { Execute statement }
Closure can be invoked in two ways : Mode one : Closure name .call() Mode two : Closure name ()
def test = { println 'hello world' }
// There are two ways to call
test.call() // Mode one
test() // Mode two 3、 Pass parameters in closures
def test = { String name -> println "hello world ${name}" } // When multiple parameters need to be passed in , Use commas to separate
test.call(" Zhang San ") // Mode one
test("zhangsan") // Mode two
// There is a default parameter in the closure be called it
def test1 = { println "hello world ${it}" }
test1.call(" Default ")
// The return value of the closure
def test2 = { String name -> println "hello world ${name}" } // Closures are not defined return Statement but still has a return value , The return value is null
def result = test2.call(" Return value ")
println(result)4、 Closures are used in conjunction with basic types
4.1、 Use upto Method to find factorial
int x = fab(5)
println x
int fab(int number) { // Factorial of
int result = 1
1.upto(number, { num -> result *= num })
return result
}4.2、 Use down Method to find factorial
int x = fab2(5)
println x
int fab2(int number) {
int result = 1
number.downto(1) {
num -> result *= num
}
return result
}4.3、 Use times Method cumulative summation
int x = fab3(5)
println x
// Cumulative sum
int fab3(int number) {
int result = 0
number.times { num -> result += num }
return result
}5、 The combination of strings and closures
5.1、each Method to traverse the string
String str = '1study groovy2'
// each Method to traverse the string
str.each {
// each The return value of the method is still the caller itself
String temp -> println temp
}5.2、find Method to find the first
str.find {
String s -> s.isNumber() // find The closure of a method must be a return value of boolean type
}5.3、findAll Method to find all eligible elements
str.findAll {
String s -> s.isNumber() // The return value is a collection
}5.4、any Method
any The value of the method is Boolean , As long as any element in the string meets the conditions in the closure, it is true, Instead of false
str.any {
String s -> s.isNumber()
}5.5、every Method
every The value of the method is Boolean , Each element in the string must meet the conditions in the closure to be true, Instead of false
str.every {
String s -> s.isNumber()
}5.6、collect Method
collect The return value of the method is list aggregate
def list2 = str.collect {
it.toUpperCase()
}
println list2.toListString()6、 Three important variables in closures :this, owner, delegate
this Keyword represents the class at the closure definition ,owner Keyword represents the class or object at the closure definition ,delegate Keyword represents any object , Default and owner Agreement
// Define a closure in a closure
def nestClosure = {
def innerClosure = {
println "innerClosure this:" + this // Points to the nearest class , Script class
println "innerClosure owner:" + owner // Point to the nearest object
println "innerClosure delegate:" + delegate // Default and owner bring into correspondence with
}
Person p = new Person()
innerClosure.delegate = p // Modify the default delegate, After modification delegate And owner The object pointed to is different
innerClosure.call()
}
nestClosure.call()
7、 The delegation strategy of closures
/* The delegation strategy of closures */
class Student {
String name
def pretty = {"My Name is ${name}"}
String toString() {
pretty.call()
}
}
class Teacher {
String name
}
Student stu = new Student(name: 'salary')
Teacher tea = new Teacher(name: ' teacher ')
// By modifying the delegate The implementation will Teacher Medium name Property substitution Student Properties in
stu.pretty.delegate = tea
// Modify strategy , Default Closure.OWNER_FIRST
stu.pretty.resolveStrategy = Closure.DELEGATE_FIRST // If delegate There is no name This attribute , Then he will be owner In search of ,Closure.DELEGATE_ONLY, If delegate There is no name When this property , You're going to report a mistake
println stu.toString()边栏推荐
- Madcap flare 2022, documentation in language or format
- Unity prevents the BTN button from being clicked continuously
- 作为过来人,写给初入职场的程序员的一些忠告
- 一文彻底弄懂工厂模式(Factory)
- 3DMAX modeling notes (I): introducing 3DMAX and creating the first model Hello World
- Traffic replication in istio Service Grid
- 机器学习之感知机
- Understand the quality assurance of open source software (OSS)
- What you must understand before you are 30
- 轻松上手Fluentd,结合 Rainbond 插件市场,日志收集更快捷
猜你喜欢

In 5g era, how to create an amazing live VR activity?

Policy deployment of firewall Foundation

History of hash index design

JS高级程序设计第 4 版:迭代器的学习

MadCap Flare 2022,语言或格式的文档

加密市场进入寒冬,是“天灾”还是“人祸”?

Tianrun cloud is about to be listed: VC tycoon Tian Suning significantly reduces his holdings and is expected to cash out HK $260million

如何实现接口异常场景测试?测试方法探索与测试工具实现

Flink status management

数据采集之:巧用布隆过滤器提取数据摘要
随机推荐
Madcap flare 2022, documentation in language or format
client-go gin的简单整合九-Create
C# 分页计算 总页数、当前页数据集合
线下实体店结合VR全景,让虚拟购物更加真实
C语言学生管理系统(开源)
看完這篇 教你玩轉滲透測試靶機Vulnhub——DriftingBlues-5
Flink状态管理
Rongyun: let the bank go to the "cloud" easily
How maxscale handles event status after MariaDB master-slave switchover -handle_ events
Sikulix选取相对位置的图片(进阶版)
VR panoramic shooting breaks the deadlock of traditional propaganda that wild geese pass without leaving traces
S7-200SMART与FANUC机器人进行Profinet通信的具体方法和步骤
融云:让银行轻松上“云”
What is bout?
After reading this article, I will teach you to play with the penetration test target vulnhub - drivetingblues-5
安装和使用protobuf-c
如何保护WordPress网站免受网络攻击?采取安全措施至关重要
七牛云上传图片
Nansen Annual Report
Unity's rich text color sets the color to be fully transparent