0

Assuming the following code snipped from a method within a groovy class, which makes use of a callback:

Service.groovy:

class Service {
    final Logger logger
}

QueryService.groovy:

class QueryService extends Service {
    def someMethod() { 
        Logger l = logger
        future.register(new SingleResultCallback<ArrayList<Document>>() {
            @Override
            void onResult(ArrayList<Document> result, MongoException e) {
                l.info('result: ' + result)      // works
                logger.info('result: ' + result) // fails
            }
        })
    }
}

There are two things I am wondering about:

  • Why is it possible to assign the logger variable to a local variable and access it from within the callback? Why can't I access a final instance variable? Does the callback method lose the reference to the class, but still have the method scope from which it is called from? What is going on internally?
  • Is there a way to still have access to an instance variable, without having to assign it every time before making use of a callback?

In case anybody is wondering as of the java reference within groovy. This is from using the upcoming mongodb java driver.

st-h
  • 2,444
  • 6
  • 37
  • 60
  • Basically this http://stackoverflow.com/questions/3251018/java-anonymous-inner-class-using-a-local-variable but groovy does not require the variable to be final – tim_yates Jun 16 '14 at 23:27
  • an anonymous inner class should be able to access an instance variable – Dror Bereznitsky Jun 17 '14 at 09:07
  • I updated the question to be more specific. Secondly I noticed this only leads to an error in case inheritance is involved. Updated that as well – st-h Jun 17 '14 at 19:56

0 Answers0