4

I'm defining a callback and would like to refer to the callback from within itself. The compiler does not like this and claims that the variable referring to the callback is not initialized. Here's the code:

final Runnable callback = new Runnable() {
    public void run() {
        if (someCondition()) {
            doStuffWith(callback); // <<--- compiler says "the local variable callback may not be initialized"
        }
    }
};
// Here callback is defined, and is certainly defined later after I actually do something with callback!

Clearly the compiler is mistaken as by the time we reach the inner method callback is defined. How do I tell the compiler that this code is fine, or how can I write it differently to placate the compiler? I haven't done much Java so I could be barking up the wrong tree here. Is there some other idiomatic way to do this? It seems like a pretty simple construct to me.

edit: Of course, this, that was too easy. Thanks for all the quick answers!

Sami Samhuri
  • 1,540
  • 17
  • 21

4 Answers4

11

Why not use:

doStuffWith(this);
Bert F
  • 85,407
  • 12
  • 106
  • 123
3

I may be wrong, but I think you want to replace doStuffWith(callback); with doStuffWith(this);.

http://download.oracle.com/javase/tutorial/java/javaOO/thiskey.html

Nikita Rybak
  • 67,365
  • 22
  • 157
  • 181
1

Have you tried using the keyword this?

brian_d
  • 11,190
  • 5
  • 47
  • 72
1

You could use this instead of callback

(just tried it, my compiler does complain about your way, but if you use this it doesnt:

final Runnable callback = new Runnable() {
    public void run() {
        if (something()) {
            doStuffWith(this);
        }
    }
};
Nanne
  • 64,065
  • 16
  • 119
  • 163