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 = 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.

Have fun.

Przemysław Jakubczyk

Software Engineer

Did you enjoy the read?

If you have any questions, don’t hesitate to ask!