【发布时间】:2018-10-31 16:29:15
【问题描述】:
我正在编写一个框架。接口是用 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>
【问题讨论】:
-
那是因为
? extends File对应Scala中的存在类型_ <: File。那么,如果按照错误消息的提示将def calculate( component: MyComponent[File] ): Unit = ???替换为def calculate(component: MyComponentFile[_ <: File]): Unit = ???会发生什么? -
@AndreyTyukin:你是对的。谢啦。很久之后才回到Scala。真的没有想到。
标签: java scala types existential-type bounded-wildcard