当前位置:网站首页>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 location coding (PE) works in transformers
- 基于SSH框架甜品商城管理系统【源码+数据库】
- Aliyundrive fuse that allows jellyfin to directly mount alicloud disks
- C generic_ Generic class
- Loot、USDT
- Go Web 编程入门:验证器
- Traffic replication in istio Service Grid
- 成都测试设备开发_单片机C语言之数组介绍
- How do I open an account on my mobile phone? Is it safe to open an account online?
- What is the difference between Z-score and deltf/f?
猜你喜欢

Transformers vit image model vector acquisition

轻松上手Fluentd,结合 Rainbond 插件市场,日志收集更快捷

【考研攻略】北京交通大学网络空间安全专业2018-2022年考研数据分析

C# Winform 相册功能,图片缩放,拖拽,预览图分页

transformers VIT图像模型向量获取

利用图片实现APP元素定位sikulix

How location coding (PE) works in transformers

Is the encryption market a "natural disaster" or a "man-made disaster" in the cold winter?

Simple integration of client go gin IX create

能让Jellyfin直接挂载阿里云盘的aliyundrive-fuse
随机推荐
一文搞懂开放源码软件(OSS)质量保证
After reading this article, I will teach you to play with the penetration test target vulnhub - drivetingblues-5
How do I open an account on my mobile phone? Is it safe to open an account online?
Groovy语法介绍
成都测试设备开发_单片机C语言之数组介绍
Are you familiar with redis cache of highly paid programmers & interview questions series 114? How are redis keys designed? Are you familiar with the memory obsolescence mechanism?
能让Jellyfin直接挂载阿里云盘的aliyundrive-fuse
Oceanbase database helps the ideal automobile intelligent production line to realize automatic recovery within 30 seconds
Chengdu test equipment development_ Array introduction of C language for single chip microcomputer
How many days are there between the two timestamps of PHP
d的嵌套赋值
Groovy之闭包
polardbx是pg还是mysql?
Installing and using protobuf-c
C#泛型_泛型类
Chip silicon and streaming technology
How location coding (PE) works in transformers
unity的富文本Text的Color设置颜色全透明
什么是Bout?
What is bout?