I would like to write the following code:
boolean found = false;
search(new SearchCallback() {
@Override void onFound(Object o) { found = true; }
});
Obviously this is not allowed, since found
needs to be final
. I can't make found
a member field for thread-safety reasons. What is the best alternative? One workaround is to define
final class MutableReference<T> {
private T value;
MutableReference(T value) { this.value = value; }
T get() { return value; }
void set(T value) { this.value = value; }
}
but this ends up taking a lot of space when formatted properly, and I'd rather not reinvent the wheel if at all possible. I could use a List<Boolean>
with a single element (either mutating that element, or else emptying the list) or even a Boolean[1]
. But everything seems to smell funny, since none of the options are being used as they were intended.
What is a reasonable way to do this?
I tend to do the boolean[1] method you mentioned:
final boolean[] found = {false};
search(new SearchCallback() {
@Override void onFound(Object o) { found[0] = true; }
});
It's a bit hackish, but it tends to be the closest thing to what you actually want
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