groovy-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Jochen Theodorou <blackd...@gmx.org>
Subject Re: Problem overloading bracket operator with CompileStatic
Date Sun, 27 Dec 2015 13:36:46 GMT
On 27.12.2015 09:18, Byron Foster wrote:
> Given the following code:
>
> ——————————————————————————————————-
> package rankspin
>
> import groovy.transform.CompileStatic
>
> trait SimpleMap<K, V> {
>    abstract V getAt(K k)
> }
>
> class Foo implements SimpleMap<String, String> {
>    String getAt(String k) {return "bar"}
> }
>
> @CompileStatic
> void go(SimpleMap map) {
>    println map["a"]
> }
>
> Foo foo = new Foo()
> go(foo)

so basically overloaded getAt in subclass plus static compilation and 
method call on the base class. Well... You have to keep in mind, that 
there is a big difference in method dispatch when it comes to static and 
dynamic typing in Groovy. In dynamic Groovy, Groovy will take the 
runtime type of an object to choose the method. In your case, the call 
site is the map["a"] aka map.getAt("a") line. The static compiler will 
only see a SimpleMap. The static compiler cannot know that this 
SimpleMap is maybe a Foo providing a better fitting getAt(String) 
method. And since the compiler cannot know that, it will take the 
getAt(K) (aka getAt(Object)) method from SimpleMap. Even if you had 
tried SimpleMap<String>, it would not have changed a thing.

In other words, a static compiler like the one of Groovy (or the one of 
Java and most other static languages cannot do this).

[..]
> Threw: org.codehaus.groovy.runtime.metaclass.MissingPropertyExceptionNoStack
> msg: No such property: password for class: rankspin.web.MyRequest
 >
> With no stack trace.  Even in the example code above it does not indicate the code site
where the error occurred.  is this correct?

This is not correct, no. The static compiler should not have used the 
dynamic way to get a property, because that is was is producing the 
stack less exception, which is normally caught before it reaches groovy 
code again and transformed into a proper exception. Since the static 
compiler is not really supposed to use those methods, it is no wonder 
the proper unwrapping is missing as well.

bye Jochen


Mime
View raw message