Implementing a Java interface with a recursive type and borders from Scala

I have a problem that can be reduced to the following Java class:

public class Foo<T extends Foo> {}

public class Bar<T extends Foo> {}

public interface AnInterface {
    public <T extends Foo, S extends Bar<T>> void doSomething(T thing, S other);
}

I am trying to implement AnInterfacefrom Scala code, and this is what the IDE tips are:

class AnImplementation extends AnInterface {
  override def doSomething[T <: Foo[_], S <: Bar[T]](thing: T, other: S): Unit = ???
}

This does not compile because the compiler generates the following error:

type arguments [T] do not conform to class Bar type parameter bounds [T <: foo.Foo[_ <: foo.Foo[_ <: foo.Foo[_ <: AnyRef]]]]

I tried to fix this in several ways; some unsuccessful experiments:

// Failing with: method doSomething has incompatible type
override def doSomething[T <: Foo[_ <: Foo[_]], S <: Bar[T]](thing: T, other: S): Unit = ???

// Failing with: illegal cyclic reference involving type T
override def doSomething[T <: Foo[_ <: T], S <: Bar[T]](thing: T, other: S): Unit = ???

// Failing with: illegal cyclic reference involving type T
override def doSomething[T <: Foo[V] forSome { type V <: T }, S <: Bar[T]](thing: T, other: S): Unit = ???

// Failing with: method doSomething has incompatible type
override def doSomething[T <: Foo[V] forSome { type V <: Foo[_] }, S <: Bar[T]](thing: T, other: S): Unit = ???

Does anyone have an idea on how to get around this problem? Is it not possible to implement such a Java interface from Scala?

+4
source share
1 answer

It looks like you are setting class parameters incorrectly. I believe this is what you need:

public class Foo<T extends Foo<T>> {}

public class Bar<T extends Foo<T>> {}

public interface AnInterface {
  <T extends Foo<T>, S extends Bar<T>> void doSomething(T thing, S other);
}

Then the implementation will be:

class AnImplementation extends AnInterface {
  override def doSomething[T <: Foo[T], S <: Bar[T]](thing:T, other:S):Unit = ???
}
0

All Articles