How can I use the most specialized type of two objects as return type?

beatbrot :

What I basically want is, that the more specialized type is inferred like in the following example:

Predicate<Object> first;
Predicate<String> second;

Predicate<String> firstOr = first.or(second);
Predicate<String> secondOr = second.or(first);

How would the method signature of or(...) look like to accomplish this?

Misha :

This can be accomplished with the following declaration of Predicate<T>::or:

default <R extends T> Predicate<R> or(Predicate<? super R> other) {
    return r -> this.test(r) || other.test(r);
}

This would allow or to create a Predicate for any subtype of both Predicate types. So, for example, the following would work:

Predicate<Object> first;
Predicate<Number> second;

Predicate<Integer> firstOr = first.or(second);
Predicate<Integer> secondOr = second.or(first);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=89864&siteId=1