Skip to content
Closures
step 1/5

Reading — step 1 of 5

Learn

~1 min readCollections and Closures

Closures are first-class blocks of code with access to surrounding variables. They're written with { ... } (curly braces — not blocks) and used everywhere:

def double = { x -> x * 2 }
double(5)               // 10

// implicit `it` for single arg
def triple = { it * 3 }
triple(5)               // 15

// multi-arg
def add = { a, b -> a + b }
add(3, 4)               // 7

Closures are why Gradle build scripts look the way they do — every task { } block is a closure invocation.

Currying:

def multiply = { a, b -> a * b }
def double = multiply.curry(2)
double(7)               // 14

with — execute closure with object as receiver:

new StringBuilder().with {
    append("Hello")
    append(", ")
    append("world")
    toString()
}

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…