代码之家  ›  专栏  ›  技术社区  ›  TrongBang

转换为Scala的Java泛型类型不接受超级类本身

  •  0
  • TrongBang  · 技术社区  · 7 年前

    我在写一个框架。这些接口是用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[文件],实际为:mycomponent[文件]。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Andrey Tyukin    7 年前

    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] .