Free preview.You're sampling one lesson — enroll free to unlock all 10 lessons and track your progress.
Enroll free
lesson

Closures and Higher-Order Functions

Closures and Higher-Order Functions

In this lesson — part of Advanced Features — you'll learn closures and higher-order functions in Groovy and why it matters in real work.

Why it matters

Functions that take or return functions unlock concise, composable code.

Key ideas

  • Functions as values
  • map / filter / reduce
  • Callbacks
  • Composition

In practice

Here's how it looks in idiomatic Groovy:

def applyTwice(x, Closure f) { f(f(x)) }
assert applyTwice(3) { it + 1 } == 5     // trailing-closure call

// closures compose and curry natively
def add = { a, b -> a + b }
def inc = add.curry(1)
assert inc(10) == 11
assert (inc >> { it * 2 })(10) == 22     // >> = forward composition

Groovy note: A Closure passed as the last argument can sit outside the parentheses (Groovy's DSL-enabling trailing-closure syntax), and closures support first-class .curry() and >>/<< composition.

Try it yourself

Exercise: In Groovy, use map and filter to get the squares of the even numbers.

Recap

You now understand closures and higher-order functions and can apply it in Groovy. Mark this lesson complete and continue to the next one.