转换为 Scala 的 Java 泛型类型不接受父类(super class)本身

标签 java scala types existential-type bounded-wildcard

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

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

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

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

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

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

最佳答案

Java的通配符类型

? extends File

对应存在类型

_ <: File

在斯卡拉。尝试更改签名

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

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

另请注意,如果 MyComponent是您控制下的 Scala 类,然后将不变类型参数更改为协变类型参数 +F也可能有效,因为这样每个 MyComponent[F] forSome { type F <: File }将是 MyComponent[File] 的特例.

关于转换为 Scala 的 Java 泛型类型不接受父类(super class)本身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50458617/

相关文章:

java - 如何在java中更新zip文件中的文本文件内容

java - 使用Java Spark加载现有Mongodb到Hive

java - 创建二进制文件 : "UnsatisfiedLinkError ibm/jzos/ZFile.fopen" after springframework. Scheduling.quartz.SchedulerFactoryBean 触发器时出错

python - 在 Scala 中如何近似 Python 的 or 运算符来进行集合比较?

typescript - 如何使用 TypeScript 从接口(interface)动态推断类型?

java - 如何在Java中打印出字符串的所有排列

scala - SQLException : unknown database with SQLite and Scala

scala - case y::ys 是什么意思?

javascript - 遇到 undefined 的问题 !== undefined

python - 如何比较 python 中的变量类型?