paul_h
paul_h

Reputation: 2051

Adding to a Groovy list in a builder-esqe way

Here's the most groovy way I've seen so far:

threads = []
threads << makeAThread("1")
threads << makeAThread("2")

But I want to do:

threads = []
threads {
    << makeAThread("1")
    << makeAThread("2")
 }

Or if I have to:

threads = []
threads {
    add(makeAThread("1"))
    add(makeAThread("2"))
 }

Therefore I'm needing builder, DSL advice.

This is what I did (modifying the answer I accepted):

threads = []
threads.with {
    add makeAThread("1")
    add makeAThread("2")
}

Upvotes: 1

Views: 88

Answers (3)

Will
Will

Reputation: 14539

If @Opal's solution doesn't suit you, you can chain << calls:

threads = [] << makeAThread("1") << makeAThread("2")

Upvotes: 1

Opal
Opal

Reputation: 84844

Why not: def threads = [makeAThread("1"), makeAThread("2")]?

Upvotes: 2

doelleri
doelleri

Reputation: 19682

You can accomplish either of your examples using with.

threads = []
threads.with {
    it << makeAThread("1")
    it << makeAThread("2")
}

or

threads = []
threads.with {
    add(makeAThread("1"))
    add(makeAThread("2"))
}

with makes every call or property access apply to the given object, in this case threads. The leftShift() operator, <<, needs an explicit left hand side, in this case it.

Upvotes: 1

Related Questions