Java – how to use the two objects of the most special type as the return type?

What I basically want is to infer a more professional type, as shown in the following example:

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

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

How does method signature or (...) achieve this goal?

Solution

This can be done with the following predicate < T >:: or declaration:

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

This will allow or create predicates for any subtype of both predicate types Therefore, for example, the following methods are feasible:

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

Predicate<Integer> firstOr = first.or(second);
Predicate<Integer> secondOr = second.or(first);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>