0Pricing
Groovy & Gradle: JVM Automation and Build Engineering · Aula

Curry e Composição de Closures

Aprofunde o conhecimento sobre closures: fixe argumentos com curry, componha funções e use memoização para criar fluxos funcionais reutilizáveis.

Curry e Composição de Closures é uma aula grátis de Groovy & Gradle: JVM Automation and Build Engineering no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Groovy & Gradle: JVM Automation and Build Engineering, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Groovy & Gradle: JVM Automation and Build Engineering inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

Beyond Basic Closures

You already know closures as anonymous blocks of code. Groovy also lets you transform closures themselves — fixing arguments, chaining them, and caching results — for powerful functional patterns.

What Is Currying?

Currying creates a new closure with some arguments pre-filled. The result takes the remaining arguments. This turns a general function into a specialized one.

Using curry()

Call curry to bind the leftmost arguments.

def add = { a, b -> a + b }
def add5 = add.curry(5)
println add5(10)

Right and nth Curry

Use rcurry to fix the rightmost argument and ncurry to fix one at a specific index.

def power = { base, exp -> base ** exp }
def square = power.rcurry(2)
println square(9)

Composing Closures

The >> and << operators compose closures so the output of one feeds the next, forming a pipeline.

def doubleIt = { it * 2 }
def inc = { it + 1 }
def pipe = doubleIt >> inc
println pipe(5)

Order of Composition

f >> g means apply f first then g, while f << g applies g first. Pick the direction that reads naturally.

def pipe2 = doubleIt << inc
println pipe2(5)

Memoization

memoize wraps a closure so repeated calls with the same arguments return a cached result instead of recomputing — ideal for expensive pure functions.

def slow = { n -> Thread.sleep(0); n * n }.memoize()
println slow(4)
println slow(4)

Bounded Memoization

Variants like memoizeAtMost and memoizeAtLeast cap cache size so memory stays bounded.

def f = { it + 1 }.memoizeAtMost(100)

Closures as Strategy Objects

Because closures are first-class, you can store them in maps and select behaviour at runtime — a clean replacement for big switch statements.

def ops = [add: { a, b -> a + b }, mul: { a, b -> a * b }]
println ops.add(2, 3)

Trampolining Recursion

For deep recursion, trampoline converts recursive closure calls into a loop, avoiding stack overflow.

def fact
fact = { n, acc = 1 -> n <= 1 ? acc : fact.trampoline(n - 1, acc * n) }.trampoline()
println fact(5)

Controlling the Delegate

A closure resolves unqualified names against its delegate. Setting resolveStrategy to DELEGATE_FIRST lets you build DSL blocks where calls target a configured object — the basis of builders.

def c = { name "Alice"; age 30 }
c.resolveStrategy = Closure.DELEGATE_FIRST

Quick Check

Test your closure transformation knowledge.

Recap

You learned advanced closure techniques:

  • curry/rcurry/ncurry pre-bind arguments
  • >> and << compose closures into pipelines
  • memoize caches results of pure functions
  • Closures stored in maps act as runtime strategies
  • trampoline makes deep recursion stack-safe

Perguntas Frequentes

A aula “Curry e Composição de Closures” é grátis?

Sim — o texto completo de “Curry e Composição de Closures” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Groovy & Gradle: JVM Automation and Build Engineering, atualize para CoddyKit PRO. O curso de Groovy & Gradle: JVM Automation and Build Engineering inclui 4 aulas no total.

O que vou aprender em “Curry e Composição de Closures”?

Aprofunde o conhecimento sobre closures: fixe argumentos com curry, componha funções e use memoização para criar fluxos funcionais reutilizáveis. Você pratica Groovy & Gradle: JVM Automation and Build Engineering com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Groovy & Gradle: JVM Automation and Build Engineering?

Nenhuma experiência prévia é necessária. Groovy & Gradle: JVM Automation and Build Engineering no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.

Quanto tempo leva a aula “Curry e Composição de Closures”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Groovy & Gradle: JVM Automation and Build Engineering?

Sim. Cada aula de Groovy & Gradle: JVM Automation and Build Engineering inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Aprimoramentos das coleções do Groovy
  2. Compreendendo closures do Groovy
  3. Padrões funcionais com Groovy
  4. Curry e Composição de Closures
← Voltar para Groovy & Gradle: JVM Automation and Build Engineering