Java lambdas/method references used as callbacks in addCallback/removeCallback style methods

34 Views Asked by At

I've read about this but I haven't found a clear answer.

Assume an API like the following:

Callback callback = new Callback();
myApi.addCallback(callback);
[...]
myApi.removeCallback(callback);

Now, if I were to replace with lambdas:

myApi.addCallback(() -> whatever());
[...]
myApi.removeCallback(() -> otherWhatever());

This obviously would not work, since we are referring different callbacks.

However, what about this?

myApi.addCallback(() -> whatever());
[...]
myApi.removeCallback(() -> whatever());

Or this?

myApi.addCallback(this::whatever);
[...]
myApi.removeCallback(this::whatever);

Or this one?

myApi.addCallback(StaticClassAccess::whatever);
[...]
myApi.removeCallback(StaticClassAccess::whatever);
0

There are 0 best solutions below