Custom putAt operator with type checking

Michael Kunz <[email protected]>
Newsgroups gmane.comp.lang.groovy.user
Message-ID <[email protected]>
Hello,

type checking for the subscript assignment operator (putAt) is broken in 
4.0.18 and 5.0.0-alpha-5

I want to overload putAt to allow a specific set of possible 
parameter/value types. But this throws
[Static type checking] - Cannot find matching method Node#getAt(int). 
Please check if the declared type is correct and if the method exists.
```
@CompileStatic
class Node {
     void putAt(int idx, String value) {}
     void putAt(int idx, Number value) {}
     static void test() {
         def n = new Node()
         n[0] = 1
         n[1] = "abc"
     }
}
Node.test()
```

If I include `Node getAt(int idx)` the error becomes
[Static type checking] - Cannot assign value of type int to variable of 
type Node

It doesn't make sense to check against the return type of getAt for any 
putAt because this isn't an assignment.
Even if I include getAt as above, and use a line like `def a = n[1] = 
"abc"` I expect `a` to be the same as the right hand side of the 
expression (the string "abc") and not of type Node (whatever the value 
could be).

I tried propagating the type of the enclosing (assignment) right hand 
side when a subscript assignment is detected in StaticTypeCheckingVisitor:
`resultType = getType(enclosingExpressionRHS)`
That produces a valid result:
```
Node n = ...
String var1 = "abc";
ScriptBytecodeAdapter.invokeMethodN(Node.class, m, (String)"putAt", new 
Object[]{1, var1});
```

This still tries to resolve getAt for the LHS during the process, but at 
least proceeds with the correct type.
The example code works as expected in a dynamic typed context.

Is there any chance to get this included in the upcoming versions?

Regards, Michael

P.S. Any future prospect on getting GROOVY-2489?
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.