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.

3
  • Basically this stackoverflow.com/questions/3251018/… but groovy does not require the variable to be final Commented Jun 16, 2014 at 23:27
  • an anonymous inner class should be able to access an instance variable Commented Jun 17, 2014 at 9: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 Commented Jun 17, 2014 at 19:56

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.