简体   繁体   English

子类型和泛型函数<? super T, ? extends T>在 Java 中

[英]Subtyping and Generics Function<? super T, ? extends T> in Java

I have an interface A and class B implementing A.我有一个接口 A 和实现 A 的类 B。

I have a method in A, called doX(Function<? super A, ? extends A> f) .我在 A 中有一个方法,称为doX(Function<? super A, ? extends A> f) When I tried to implement it in B, by writing <T extends A> doX(Function<? super B, T> f) , it doesn't compile.当我尝试在 B 中实现它时,通过编写<T extends A> doX(Function<? super B, T> f) ,它不会编译。 I tried a variant of other possible generics also doesn't work.我尝试了其他可能的泛型的变体也不起作用。 Basically, my function wants to take in itself, and spits out some other item implementing A. By using PECS, it becomes <? super B>基本上,我的函数想要自己接受,并吐出一些其他实现 A 的项目。通过使用 PECS,它变成<? super B> <? super B> , however it is wrong. <? super B> ,然而这是错误的。 Now I am totally clueless about what I should write.现在我完全不知道我应该写什么。

...my function wants to take in itself, and spits out some other item implementing A ...我的函数想要吸收自身,并吐出一些其他实现 A 的项目

If this is your only requirement, we can do away with super clause.如果这是您唯一的要求,我们可以取消super条款。

  1. You said the function should take its current instance as input.您说该函数应将其当前实例作为输入。 We can acheive it by introducing a type parameter at interface A level.我们可以通过在interface A层引入一个类型参数来interface A
  2. For returning another implementation of interface A , we can introduce a type parameter at the method level.为了返回interface A另一个实现,我们可以在方法级别引入一个类型参数。

Below is the complete code下面是完整的代码

public class Subtyping {
    private interface A<T extends A<T>> {
        <S extends A<S>> S doX(Function<T, S> f);
    }
    private static class B implements A<B> {
        @Override
        public <S extends A<S>> S doX(Function<B, S> f) {
                return f.apply(this);
        }
    }
    private static class C implements A<C> {
        @Override
        public <S extends A<S>> S doX(Function<C, S> f) {
            return null;
        }
    }
    public static void main(String[] args) {
        B b = new B();
        C result = b.doX(v -> new C());
        System.out.println(result);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM