For example, i have SimpleCallback class
public class SimpleCallback<T> implements Callback<T> {
private SuccessListener<T> successListener;
private ErrorListener errorListener;
protected SimpleCallback() {
}
public static <C> SimpleCallback<C> success(SuccessListener<C> listener) {
SimpleCallback<C> callback = new SimpleCallback<>();
callback.successListener = listener;
return callback;
}
public SimpleCallback<T> error(ErrorListener errorListener) {
this.errorListener = errorListener;
return this;
}
@Override
public void onComplete(T result) {
notifySuccess(result);
}
@Override
public void onError() {
notifyError();
}
public interface SuccessListener<T> {
void onSuccess(T result);
}
public interface ErrorListener {
void onError();
}
}
Now i want to use this callback for get cats asynchronous:
SimpleCallback<List<Cat>> callback = SimpleCallback
.success(cats -> cats.forEach(Cat::meow));
It's ok now, but when i want add error listener my cats become raw objects
SimpleCallback<List<Cat>> callback = SimpleCallback
.success(cats -> cats.forEach(Cat::meow)) <-- Here cats become objects
.error(() -> System.out.println("Cats error"));
One of solution use explicit generic type:
SimpleCallback<List<Cat>> callback = SimpleCallback.<List<Cat>>
.success(cats -> cats.forEach(Cat::meow))
.error(() -> System.out.println("Cats error"));
But it looks little bit ugly. So is any way to create callback without explicit generic type?
UPD: I think @Jesper offered good solution
Another solution is to provide the type of the argument of the lambda expression explicitly:
.success((List<Cat> cats) -> cats.forEach(Cat::meow))