代码之家  ›  专栏  ›  技术社区  ›  beatbrot

如何使用两个对象中最特殊的类型作为返回类型?

  •  3
  • beatbrot  · 技术社区  · 7 年前

    我基本上想要的是,更专业化的类型被推断为如下示例:

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

    签名的方法 or(...)

    2 回复  |  直到 7 年前
        1
  •  4
  •   Misha    7 年前

    Predicate<T>::or :

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

    这将允许 or 创建 Predicate 谓语 类型。因此,举例来说,以下方法可行:

    Predicate<Object> first;
    Predicate<Number> second;
    
    Predicate<Integer> firstOr = first.or(second);
    Predicate<Integer> secondOr = second.or(first);
    
        2
  •  2
  •   marstran    7 年前

    我想你需要两个过载才能工作。但是,由于重载之间的唯一区别在于类型参数,因此它们会因为擦除而发生冲突。因此,您需要对它们进行不同的命名(这将不再使它们成为实际的重载)。

    这可能是签名:

    /* In this case, the input Predicate has the most specific type.
     * Use this in the first.or(second) case
     */
    public <R extends T> Predicate<R> or1(Predicate<R> pred);
    
    /* In this case, the receiver Predicate has the most specific type.
     * Use this in the second.or(first) case
     */
    public Predicate<T> or2(Predicate<? super T> pred);
    

    first second 有那种类型 Predicate<String> )