Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Difference in static & dynamic code dispatching to field or getter
import groovy.transform.*
//@CompileStatic
class Person {
String name
private List<Person> friends
String friendNames() {
friends.collect { it.name }.join(", ")
}
}
assert new Person(name: "Rob").friendNames() == ""
@robfletcher

This comment has been minimized.

Copy link
Owner Author

robfletcher commented Dec 12, 2014

Without @CompileStatic the code works as friends on line 9 dispatches to getFriends(). With @CompileStatic it dispatches direct to the private field and results in an NPE.

@robfletcher

This comment has been minimized.

Copy link
Owner Author

robfletcher commented Dec 12, 2014

Interestingly if I change from friends.collect { it.name } to friends.name the dispatch changes!

@robfletcher

This comment has been minimized.

Copy link
Owner Author

robfletcher commented Dec 12, 2014

Tried it in 2.3.8 and 2.4.0-beta-4 with the same result.

@robfletcher

This comment has been minimized.

Copy link
Owner Author

robfletcher commented Dec 12, 2014

I've updated the gist now as apparently this is nothing to do with the presence of a getter. It's simply that dynamically compiled Groovy allows for calling certain GDK methods (all of them? only iterators?) on null.

@lhotari

This comment has been minimized.

Copy link

lhotari commented Dec 12, 2014

I think I've run in to this and reported a bug. I'll try to look it up.

@lhotari

This comment has been minimized.

Copy link

lhotari commented Dec 12, 2014

My problem was different indeed, it was http://jira.codehaus.org/browse/GROOVY-7098 . Fixed in 2.3.8 already .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.