2016-09-08 67 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