Search code examples
groovyparametersjvmargumentssuperclass

Passing String argument to Object method parameter in Groovy


Recently, I was asked to solve a strange error in Groovy. The code looks like this:

int OQ = line.getAttribute("OrderedQuantity");
line.setAttribute("OrderedQuantity", OQ.toString(OQ+50));

and the error message looks like this:

No signature of method: 
oracle.apps.scm.doo.common.extensions.Line.setAttribute() is applicable for argument types: (java.lang.String, java.lang.String) values: [OrderedQuantity, 59]
Possible solutions: setAttribute(java.lang.String, java.lang.Object), setAttribute(java.lang.String, java.lang.Object), getAttribute(java.lang.String), getAttribute(java.lang.String), getAttribute(java.lang.String). (DOO-2685874)

Coming from a Java background, I found this to be confusing. In Java we would instead have done:

line.setAttribute("OrderedQuantity", Integer.toString(OQ+50));

But, I tested the following code in a Groovy console and it seems to work:

int x = 5;
print x.toString(x+2);​

Output is

7

which is correct.

The "possible solutions" in the error message suggests that the setAttribute method accepts a String as the first argument and an Object as the second argument. Clearly, the original code is correct (atleast in Java) since String is also an Object so the setAttribute(java.lang.String, java.lang.Object) method signature should be valid.

What could be the reason for the error? Can subclass arguments be passed into superclass method parameters in Groovy?

As an aside, I have noticed that the same method signatures are repeated multiple times. In Java it is not possible to have two identical method signatures. Why do multiple method signatures appear in the error message?


Solution

  • Following code works:

    def OQ = line.getAttribute("OrderedQuantity") + 50;
    line.setAttribute("OrderedQuantity", OQ);
    

    The problem is solved but I will accept anybody's answer that explains why it works.