【问题标题】:Java Wildcard Generic Type Interop From Scala来自 Scala 的 Java 通配符通用类型互操作
【发布时间】:2016-09-08 15:28:26
【问题描述】:

我正在用 scala 编写,我正在处理一个 Java API,它返回一个 List<? extends IResource>,其中IResource 是通用父接口 (the details, if it helps)。

我正在尝试将 IResource 添加到该方法返回的列表中,但我无法编译我的代码(Patient is a java class which implements IResourcegetContainedResources 返回 @987654329 @):

这是我的原始代码

val patient = new Patient()
patient.setId(ID)
val patientASResource: IResource = patient
entry.getResource.getContained.getContainedResources.add(patient)

这是我得到的错误:

type mismatch;
  found   : patientASResource.type (with underlying type ca.uhn.fhir.model.api.IResource)
  required: ?0 where type ?0 <: ca.uhn.fhir.model.api.IResource
         entry.getResource.getContained.getContainedResources.add(patientASResource)
                                                                  ^
 one error found

请注意,我正在尝试将我输入的patientASResource 添加到界面IResource。尝试添加 patient(实现接口的类)会出现更严重的错误消息。

我尝试过的其他事情:

//From what I understand of "Java wildcards" per here: http://stackoverflow.com/a/21805492/2741287
type Col = java.util.Collection[_ <: IResource]
val resList: Col = entry.getResource.getContained.getContainedResources
val lst: Col = asJavaCollection(List(patient))
resList.addAll(lst)

也不行,它返回类似:

type mismatch
found : java.util.Collection[_$1(in method transformUserBGs)] where type _$1(in method transformUserBGs) <: ca.uhn.fhir.model.api.IResource 
 required: java.util.Collection[_ <: _$1(in type Col)]
 resList.addAll(lst)
 ^

【问题讨论】:

    标签: scala


    【解决方案1】:

    问题不在于互操作。这绝对不应该编译,等效的 Java 代码也不应该编译。

    List&lt;? extends IResource&gt; 表示它可以是List&lt;IResource&gt;List&lt;Patient&gt;List&lt;SomeSubclassOfPatient&gt;List&lt;SomeOtherResourceUnrelatedToPatient&gt; 等,而你不知道是哪个。因此,不允许将Patient(或向上转换后的IResource)添加到此类列表中。

    如果您以某种方式知道在您的特定情况下entry 使得entry.getResource.getContained.getContainedResources 返回List[IResource]List[Patient],您应该尝试通过在覆盖getContainedResources 时指定它来静态确保这一点。如果这是不可能的,最后的办法是强制转换:

    entry.getResource.getContained.
      getContainedResources.asInstanceOf[java.util.List[IResource]].add(patient)
    

    重申一下:如果可能的话,你应该避免这种情况。

    【讨论】:

    • 感谢您的 cmets 帮助我意识到我的问题,即我不理解 Existential types/java 的通配符。
    猜你喜欢
    • 1970-01-01
    • 2014-01-21
    • 2013-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-03
    • 1970-01-01
    相关资源
    最近更新 更多