当前位置: 动力学知识库 > 问答 > 编程问答 >

Scala interop with Java questionmark generics

问题描述:

EDIT I have made the example self-contained.

Suppose in java I have

src/main/java/FooFactory.java

interface FooFactory {

Foo<?> create();

<T> void enhance(Foo<T> foo, FooEnhancer<? super T> enhancer);

}

and src/main/java/Foo.java

interface Foo<T> {}

and src/main/java/FooEnhancer.java

interface FooEnhancer<T> {}

(and you can't change these interfaces because they belong to someone else.)

Then in scala you have

object DummyFooEnhancer extends FooEnhancer[Any]

trait FooHdlr {

def fooFactory: FooFactory

val foo = fooFactory.create

fooFactory.enhance(foo, DummyFooEnhancer)

}

This doesn't compile because FooEnhancer and Foo are invariant but foo is a Foo<?> whereas DummyFooEnhancer is a Foo[Any]. Changing Any to AnyRef doesn't work for the same reason.

Then I reasoned that, well, ? is a specific type that is certainly not known at compile time and that may not necessarily be AnyRef/Object, so what if I do this?

case class DummyFooEnhancer[T] extends FooEnhancer[T]

trait FooHdlr {

def fooFactory: FooFactory

val foo = fooFactory.create

fooFactory.enhance(foo, new DummyFooEnhancer)

}

But this causes scalac to stackoverflow! It's looping with

at scala.reflect.internal.Types$TypeVar.isGround(Types.scala:3082)

calling itself.

Interestingly if I replace ? super T with T it works fine, but in real life I can't do this because it's in code I don't control

分享给朋友:
您可能感兴趣的文章:
随机阅读: