1

I'm very new to Groovy but I couldn't find an answer to my question over web. I've a very simple map: Map<String, Object>. I need to update values of this map using a method while iterating. I've found a way to do it:

Map<String, Object> newMap = myMap.each { it -> it.value = getValue(it.key) }

I couldn't understand why this doesn't work:

Map<String, Object> newMap = myMap.each { k,v -> v = getValue(k) }

Thanks in advance.

GokcenG
  • 2,771
  • 2
  • 25
  • 40
  • 2
    For the same reason calling `void run( int a ) { a++ }` doesn't change `a` outside of the method call – tim_yates Jan 22 '14 at 20:28

1 Answers1

1

If you know Java, then consider the code below as an crude approximation to what Groovy is doing. Be sure to examine the comment in the eachBlock regarding assignment to v

import java.util.*;

public class Mapper {

    public void each(Map<String,Object> map) {
        for (String k : map.keySet()) {
            Object v = map.get(k);
            eachBlock(k,v);
        }
    }

    public void eachBlock(String k, Object v) {
        System.out.println("k: " + k + " , v: " + v);
        // assigning to v here is local, on the stack:
        // v = new Integer(22);
    }

    public static void main(String... args) {
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("abc", new Integer(99));
        map.put("def", new Double(3.14d));
        map.put("ijk", new ArrayList());

        Mapper mapper = new Mapper();
        mapper.each(map);
    }
}
Michael Easter
  • 23,733
  • 7
  • 76
  • 107