Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 926
extraRice Avatar asked Aug 03 '15 02:08

extraRice


People also ask

Can we use spread operator in Java?

There is a good reason why this is not possible in Java. You can have another method that takes say 4 integer arguments. You would not know at compile time which one to call since it depends on the length of the list which is only known at run time.

What does ==~ mean in Groovy?

In Groovy, the ==~ operator is "Regex match". Examples would be: "1234" ==~ /\d+/ -> evaluates to true. "nonumbers" ==~ /\d+/ -> evaluates to false.


1 Answers

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;
}
like image 134
Robby Cornelissen Avatar answered Sep 28 '22 10:09

Robby Cornelissen