当前位置:网站首页>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()边栏推荐
- How many days are there between the two timestamps of PHP
- C # WinForm photo album function, picture zooming, dragging, preview Pagination
- Cosmos、Polkadot
- Verification code is the natural enemy of automation? See how the great God solved it
- 《Kubernetes监控篇:Grafana通过自动化方式添加datasource和dashboard》
- 数据库中如何使用SQL进行修改&删除
- 成都测试设备开发_单片机C语言之数组介绍
- 怎样在手机上开户?网上开户安全么?
- 2022oracle数据库安装及使用
- Perceptron of machine learning
猜你喜欢

位置编码(PE)是如何在Transformers中发挥作用的

CVE-2022-22965复现

Madcap flare 2022, documentation in language or format

Verification code is the natural enemy of automation? See how the great God solved it

【无标题】

Cve - 2022 - 22965 Resume

线下实体店结合VR全景,让虚拟购物更加真实

Rongyun: let the bank go to the "cloud" easily

Transformers vit image model vector acquisition

How to implement interface exception scenario testing? Exploration of test methods and implementation of test tools
随机推荐
JS高级程序设计第 4 版:迭代器的学习
Excuse me, is Zhongyan futures reliable? Is the fund safe?
php两个时间戳相隔多少天
一文彻底弄懂单例模式(Singleton)
C#泛型_泛型类
Basic usage and FAQs of jasperreport report report generation tool
ThoughtWorks.QRCode和ZXing.Net 二维码,网址可以直接跳转
Summary of patent blog writing
unity的富文本Text的Color设置颜色全透明
Mysql学习笔记2022
Error: Unable to find a match: lrzsz的解决方法
金融应用如何解决金额精度问题(以Quorum、golang为例)
What is the difference between Z-score and deltf/f?
Support vector machine for machine learning
MadCap Flare 2022,语言或格式的文档
一文彻底弄懂建造者模式(Builder)
Kukai TV ADB
【考研攻略】北京交通大学网络空间安全专业2018-2022年考研数据分析
Common real machine debugging plug-ins for unity commercial games
Nansen Annual Report