2016-09-08 26 views
1

我正在写scala,我正在处理一个Java API,它返回一个 List<? extends IResource>,其中IResource是一个通用的父接口(the details, if it helps)。Java通配符类型互操作从斯卡拉

我想一个IResource添加到由该方法返回的名单,但我不能让我的代码编译(Patientis a java class which implementsIResource,并且getContainedResources返回List<? extends IResource>):

这里是我的原代码

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) 
^ 

回答

1

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

List<? extends IResource>意味着它可以是一个List<IResource>List<Patient>List<SomeSubclassOfPatient>List<SomeOtherResourceUnrelatedToPatient>等,你不知道哪个。因此,不允许在上传后添加Patient(或上传后的IResource)。

假如你不小心知道,在您的具体情况entry是这样的:entry.getResource.getContained.getContainedResources返回List[IResource]List[Patient],你应该尝试通过重写getContainedResources时指定该静态保证这一点。如果这是不可能的,最后的办法是到施放:

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

只是重申:如果你要避免这种情况在所有可能的。

+0

感谢您的评论帮助我意识到我的问题,这是我不了解存在类型/ java的通配符。 – user2741287