charrison
charrison

Reputation: 857

Groovy: receiver-modifying equivalent of collect()?

I need to loop through an array and perform a function on each element. After this operation I will no longer need the original array. Does Groovy have a way to modify the original array in place, without creating a new object?

For example, instead of

a = [1, 2, 3]
a = a.collect { elem -> elem * 2 }

I want to do:

a.collectInPlace { elem -> elem * 2 }

So that a becomes [2, 4, 6]

In Ruby for example, the array class has a #collect method, which returns the modified array, and also #collect!, which modifies the array in place and returns nil.

Upvotes: 0

Views: 485

Answers (1)

Emmanuel Rosa
Emmanuel Rosa

Reputation: 9885

No, Groovy does not provide such a method. But, you can create your own. It may be a terrible idea, but you can still do it :) Here's an example:

/*
 * A Groovy category to add collectInPlace()
 * to the List interface.
 */
class ListCategory {

    /*
     * Calls the Closure for each element in the List
     * and replaces the element with the output of the
     * Closure.
     */
    static List collectInPlace(List list, Closure closure) {
        (0..<list.size()).each { index ->
            list[index] = closure(list[index])
        }

        return list
    }
}

def a = [1, 2, 3]
def b

use(ListCategory) {
    b = a.collectInPlace { elem -> elem * 2 }
}

assert a.is(b) // Groovy's Object.is(Object) is the equivalent of Java's == operator.
assert b == [2, 4, 6]

Upvotes: 1

Related Questions