extraRice
extraRice

Reputation: 333

Java translation of groovy spread operator

Given:

class Car {
    String make
    String model
}
def cars = [
       new Car(make: 'Peugeot', model: '508'),
       new Car(make: 'Renault', model: 'Clio')]     

def makes = cars*.make  

How does cars*.make works behind the scene in java? Does it create a new Map object in the heap and combine two maps?

Upvotes: 5

Views: 1967

Answers (1)

Robby Cornelissen
Robby Cornelissen

Reputation: 97152

I took a look at the bytecode, and the only maps involved are the maps that are created to initialize the Car objects.

Once the two car objects are initialized, they are put into a list. The spread operator translates (in this case) to a call to ScriptBytecodeAdapter.getPropertySpreadSafe.

Looking at the source of that method, you'll see that it basically just creates a new ArrayList and adds the requested property (in this case make) of each object:

public static Object More ...getPropertySpreadSafe(Class senderClass, Object receiver, String messageName) throws Throwable {
    if (receiver == null) return null;

    List answer = new ArrayList();
    for (Iterator it = InvokerHelper.asIterator(receiver); it.hasNext();) {
        answer.add(getPropertySafe(senderClass, it.next(), messageName));
    }
    return answer;
}

Upvotes: 5

Related Questions