Groovy (闭包)

闭包是一个短的匿名代码块。它通常跨越几行代码。一个方法甚至可以将代码块作为参数。它们是匿名的。

package com.klvchen.test2

class ClosureTest {
	static void main(String[] args) {
		def clos = {println "Hello World"};
		clos.call();
	}
}

在上面的例子中,代码行 {println "Hello World"}被称为闭包。此标识符引用的代码块可以使用 call 语句执行。

闭包中的形式参数

闭包也可以包含形式参数,以使它们更有用,就像Groovy中的方法一样。

package com.klvchen.test2

class ClosureTest {
	static void main(String[] args) {
		def clos = {param->println "Hello ${param}"};
		clos.call("World");
	}
}

在上面的代码示例中,注意使用$ {param},这导致closure接受一个参数。当通过clos.call语句调用闭包时,我们现在可以选择将一个参数传递给闭包。

这里的'it'是Groovy中的关键字。可以使用被称为它的隐式单个参数

package com.klvchen.test2

class ClosureTest {
	static void main(String[] args) {
		def clos = {println "Hello ${it}"};
		clos.call("World");
	}
}

闭包和变量

更正式地,闭包可以在定义闭包时引用变量。

package com.klvchen.test2

class ClosureTest {
	static void main(String[] args) {
		def str1 = "Hello";
		def clos = {param -> println "${str1} ${param}"};
		clos.call("World");
		
		str1 = "Welcome";
		clos.call("World");
	}
}

在上面的例子中,除了向闭包传递参数之外,我们还定义了一个名为str1的变量。闭包也接受变量和参数。

在方法中使用闭包

闭包也可以用作方法的参数。在Groovy中,很多用于数据类型(例如列表和集合)的内置方法都有闭包作为参数类型。

package com.klvchen.test2

class ClosureTest {
	def static Display(clo) {
		// This time the $param parameter gets replaced by the string "Inner"
		clo.call("Inner");
	}
	
	static void main(String[] args) {
		def str1 = "Hello";
		def clos = {param -> println "${str1} ${param}"};
		clos.call("World");
		
		// We are now changing the value of the String str1 which is referenced in the closure
		str1 = "Welcome";
		clos.call("World");
		
		// Passing our closure to a method
		ClosureTest.Display(clos);
	}
}

在上述示例中,

  • 我们定义一个名为Display的静态方法,它将闭包作为参数。
  • 然后我们在我们的main方法中定义一个闭包,并将它作为一个参数传递给我们的Display方法。

集合和字符串中的闭包

几个 List,Map 和 String 方法接受一个闭包作为参数。

使用闭包和列表

以下示例显示如何使用闭包与列表。在下面的例子中,我们首先定义一个简单的值列表。列表集合类型然后定义一个名为 .each 的函数。此函数将闭包作为参数,并将闭包应用于列表的每个元素

package com.klvchen.test2

class ClosureTest {
	static void main(String[] args) {
		def lst = [11, 12, 13, 14];
		lst.each { println it };
	
	}
}

使用映射闭包

以下示例显示了如何使用闭包。在下面的例子中,我们首先定义一个简单的关键值项Map。然后,映射集合类型定义一个名为.each的函数。此函数将闭包作为参数,并将闭包应用于映射的每个键值对。

package com.klvchen.test2

class ClosureTest {
	static void main(String[] args) {
		def mp = ["TopicName" : "Maps", "TopicDescription" : "Methods in Maps"];
		mp.each { println it };
		System.out.println("=================================");
		mp.each { println "${it.key} maps to: ${it.value}" }
	
	}
}

通常,我们可能希望遍历集合的成员,并且仅当元素满足一些标准时应用一些逻辑。这很容易用闭包中的条件语句来处理。

package com.klvchen.test2

class ClosureTest {
	static void main(String[] args) {
		def lst = [1, 2, 3, 4];
		lst.each { println it };
		System.out.println("The list will only display those numbers which are divisible by 2");
		lst.each { num -> if(num % 2 == 0) println num }
	
	}
}

闭包使用的方法


参考:https://www.w3cschool.cn/groovy/groovy_closures.html

posted @ 2021-03-27 13:48  klvchen  阅读(168)  评论(0)    收藏  举报