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!
Why not use:
doStuffWith(this);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With