February 18, 2013 | 1min read
How to create Inner classes - Groovy vs. Java
Testing Android with RoboSpock is a walk in the park - Groovy and Spock/Robospock do the hard work for you. It’s always nice to have a good clear code, well formatted, object oriented etc. Recently I’ve been redeveloping android-image-cache and I came across a very interesting problem. Groovy and Java are good friends but the differ in some cases, especially when it comes with Inner Classes. I have a class called CacheTask in ImageCache which is not static so the creation of this object must go via ImageCache object. In Java you could write
ImageCache cache = new ImageCache() ImageCache.CacheTask task = cache.new ImageCache.CacheTask("new name")
There’s a long stackoverflow discussion on why the syntax is correct. But let’s go back to Groovy. The code snippet won’t work because Groovy will try to find a method signature starting with ‘new’. In the same stackoverflow thread there is tricky solution how to do it Groovy
def cache = new ImageCache() def task = new CacheTask(cache, "new name")
IntelliJ underlines the constructor because in the code there’s no constructor matching these arguments. The code works because the generated bytecode includes a hidden constructor where IDE just checks the .groovy file.
You might also like
January 28, 2020
Accessibility—Mistakes to Avoid When Implementing it in an Android App
Not only UX designers but also developers should have accessibility in mind. Learn how to use TalkBack and make using your Android app easier for those visually impaired.