Mastering Closures: Passing Functions as Parameters in Java, Groovy, Python, and Go
This article compares how Java, Groovy, Python, and Go implement closures and treat functions as parameters, showing concrete syntax for defining single‑parameter, multi‑parameter, and parameter‑less closures, as well as returning and invoking them within methods.
Java
Java uses functional interfaces such as java.util.function.Function, java.util.function.BiFunction, and java.util.function.Supplier to represent closures with different arities.
Single‑parameter closure: Function<Integer, Integer> plus10 = f -> f * 10; Two‑parameter closure:
BiFunction<Integer, Integer, Integer> pluss = (x, y) -> {
return x * y;
};No‑parameter closure:
Supplier<Integer> plu = () -> {
return getMark();
};Returning a closure from a method:
static Function<Integer, Integer> have(int i) {
return f -> f + i;
}Using a closure as a parameter:
private static int funTestInt(int dir, Function<Integer, Integer> function) {
return function.apply(dir);
}Groovy
Groovy’s syntax is more flexible; closures are created with { ... } or arrow syntax.
No‑parameter: def plussss = { return 10 } or def plusss = () -> 10 Single‑parameter: def pluss = f -> f + 10 (alternatives shown)
Multiple parameters: def plus = { x, y -> return x + y * 2 } Returning a closure:
static Closure<Integer> plus3(int i) {
return { f -> return f * i }
}Using a closure as a parameter:
static int plus2(int i, Closure closure) {
return closure(i, 32)
}Python
Python uses lambda expressions for simple closures.
Single‑parameter: ff = lambda f: f + 19 Multiple parameters: ss = lambda x, y: x * y + 1 Returning a closure from a function:
def test2(me):
def test3(name):
print(me + "方法")
print(name)
return test3Passing a closure as an argument:
def testt(ff):
return ff(3)Golang
Go treats functions as first‑class values; closures are defined with func literals.
Single‑parameter closure example: ff := func(f int) int { return f * 11 } Returning a closure from a function:
func out() func(int) int {
return func(y int) int {
return y + 21
}
}Using a closure as a parameter:
func FunMethod(i int, f func(int) int) {
f(i * 3)
}Overall, the article demonstrates that while Java requires distinct functional‑interface types for different signatures, Groovy, Python, and Go provide more concise and flexible ways to define, return, and pass closures as parameters.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
