0

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.

4
  • 2
    Why would you want to? You would lose any firm of thread safety at the premium of saving a tiny amount of memory
    – tim_yates
    Mar 9, 2016 at 13:18
  • And returning null from the method would stop you having any sort of fluency in your code
    – tim_yates
    Mar 9, 2016 at 13:42
  • I don't agree with the point on code fluency (I think the extra assignment is messy), and thread safety is not an issue for me, whereas speed and memory efficiency are
    – charrison
    Mar 9, 2016 at 16:32
  • 1
    My point about fluency is that you can do a.collect { it * 2 }.findAll { it % 3 }.inject { a, b -> a + b }. With your version, you can't chain things together...
    – tim_yates
    Mar 9, 2016 at 16:48

1 Answer 1

1

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]
3
  • Thanks Emmanuel! I'll have another look in a day or two. Please can you explain why you think it is/may be a terrible idea? I'm pretty new to Groovy and I found the self-modifying methods in Ruby very convenient
    – charrison
    Mar 9, 2016 at 16:35
  • or just: List.metaClass.collectInPlace = { Closure closure -> list.eachWithIndex { it, idx -> delegate[idx] = closure(it) } ; null } in place of the Category and the use block requirement
    – tim_yates
    Mar 9, 2016 at 16:51
  • 1
    @charrison, it's a terrible idea because working with immutable objects is safer. See ibm.com/developerworks/library/j-jtp02183 Mar 9, 2016 at 19:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.