简体   繁体   中英

Implementing a Java interface featuring recursive type and bounds from Scala

I have a problem that can be summarised by the following Java classes:

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 AnInterface from Scala code and this is what my IDE advices:

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

This doesn't compile as the compiler produces the following error:

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

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

// 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 about how to get around this issue? Is it not possible to implement such a Java interface from Scala?

It looks like you're not parameterizing the classes correctly. I believe this is what you're after:

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 becomes:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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