Java 转换为 Scala 的通用类型不接受 super class 本身

Java Generic Type Converted to Scala does not accept super class itself

我正在写一个框架。这些接口是用 Java 代码编写和编译的。客户端使用 Scala 和那些接口。这是界面的示例。

public interface Context {
   MyComponent<? extends File> getComponent();
}

现在我的scala代码使用的接口如下。

val component = context.getComponent();
println(calculate(component));

def calculate( component: MyComponent[File] ): Unit = ???

Scala 编译器在第 2 行为 println(calculate(component)) 抛出错误。错误是:类型不匹配,预期:MyComponent[File],实际:MyComponent[_ <: File].

Java的通配符类型

? extends File

对应存在类型

_ <: File

在 Scala 中。尝试更改签名

def calculate(component: MyComponent[File]): Unit = ???

def calculate(component: MyComponent[_ <: File]): Unit = ???

另请注意,如果 MyComponent 是受您控制的 Scala-class,则将不变类型参数更改为协变类型参数 +F 也可能有效,因为那样的话每个 MyComponent[F] forSome { type F <: File } 都是 MyComponent[File].

的特例