1

In Java I can do this:

    interface BaseInterface {}

    interface ExtendsInterface extends BaseInterface {}

    public interface ProblemInterface<E extends BaseInterface> {
        void method(E baseInterface);
    }

    class Main {
        public static void main (String [ ] args) {
            ProblemInterface<ExtendsInterface> problemInterfaceExtendsInterface = new ProblemInterface<ExtendsInterface>() {
                @Override
                public void method(ExtendsInterface baseInterface) {}
            };

             ProblemInterface<? extends BaseInterface> problemInterfaceBaseInterface = problemInterfaceExtendsInterface;
        }
    }

In Kotlin:

    interface BaseInterface

    interface ExtendsInterface: BaseInterface

    interface ProblemInterface<out E : BaseInterface> {
       fun method(baseInterface: E)
    }       

    val problemInterfaceExtendsInterface: ProblemInterface<ExtendsInterface> = object : ProblemInterface<ExtendsInterface> {
        override fun method(baseInterface: ExtendsInterface) {}
    }

    val problemInterfaceBaseInterface: ProblemInterface<BaseInterface> = problemInterfaceExtendsInterface

But the problem is: using covariant (out) but Type parameter occurs in 'in' position

Any idea to solve this? How I can do to works the same code in Java/Kotlin? Thanks

  • Solve it by declaring `in E` instead of `out E`. Clearly your interface is contravariant with respect to it. – Marko Topolnik Jun 13 '18 at 10:21
  • `out` types cannot appear as arguments of functions. They can only be returned (hence `out`). – Strelok Jun 13 '18 at 10:30
  • @MarkoTopolnik but declaring in E then I can't use val problemInterfaceBaseInterface: ProblemInterface = problemInterfaceExtendsInterface – user2855001 Jun 13 '18 at 11:51
  • @Strelok I know, I look a solution to use: val problemInterfaceBaseInterface: ProblemInterface = problemInterfaceExtendsInterface keeping fun method(baseInterface: E) in ProblemInterface interface – user2855001 Jun 13 '18 at 12:00
  • That's because the type system is right and you're wrong: you can't treat a `ProblemInterface` as if it was a `ProblemInterface`. Its `method` doesn't accept all instances of `BaseInterface`. – Marko Topolnik Jun 13 '18 at 12:00
  • I added the same code in Java and works fine, what's wrong with kotlin? – user2855001 Jun 14 '18 at 06:26
  • Nothing wrong with Kotlin, but wrong again with your Java code. Since Java only supports use-site variance declaration, you were allowed to declare `ProblemInterface extends BaseInterface>`. Now you can't call `method()` without a compiler error. – Marko Topolnik Jun 14 '18 at 06:54
  • You might also note that `ProblemInterface` didn't declare `E` as a covariant type parameter (it's not equivalent to `out E`). It just enforced an upper bound on `E`. – Marko Topolnik Jun 14 '18 at 07:45

0 Answers0