[英]Passing scala `Comparable` array to java generic method
我的圖書館里有這些課:
// This is java
public abstract class Property<T extends Comparable<T>> {
public static Property<T> create(String str) { /* Some code */ }
}
public class PropertyInt extends Property<Integer> {
public static PropertyInt create(String str) { /* Some code */ }
}
public class PropertyDouble extends Property<Double> {
public static PropertyDouble create(String str) { /* Some code */ }
}
並且有一個方法接受我要使用的Property
列表:
public void state(Property... properties) {
/* some code */
}
我無法更改上述內容,因為它們來自圖書館。 在scala中,我有以下代碼嘗試將數組傳遞給void state(Property...)
:
// This is scala
val propertyInt = PropertyInt.create("index")
val propertyDouble = PropertyDouble.create("coeff")
state(Array[Property](proeprtyInt, propertyDouble)))
代碼的最后一行有一個錯誤: Type mismatch, expected Property[_ <: Comparable[T]], actual Array[Property]
如何解決此問題?
注意:這是一些更復雜的代碼的簡化版本。 在實際代碼中, Property<T extends Comparable<T>>
實現了接口IProperty<T extends Comparable<T>>
並且IProperty
被用作state
的參數。
編輯:以下
val properties = Array(propertyInt.asInstanceOf[IProperty[_ <: Comparable[_]]],
propertyDouble.asInstanceOf[IProperty[_ <: Comparable[_]]])
state(properties)
給出錯誤
Error:(54, 33) type mismatch;
found : Array[Property[_ >: _$3 with _$1 <: Comparable[_]]] where type _$1 <: Comparable[_], type _$3 <: Comparable[_]
required: Property[?0] forSome { type ?0 <: Comparable[?0] }
state(properties)
^
您需要將state
參數更改為通用:
public static void state(Property<?> ... properties) {
/* some code */
}
然后,您可以執行以下操作:
// This is scala
val propertyInt = PropertyInt.create("index")
val propertyDouble = PropertyDouble.create("coeff")
state(propertyInt, propertyDouble)
state(Array(propertyInt, propertyDouble):_*)
UPD如果你不能改變的簽名state
,你仍然可以調用它像這樣:
state(Array[Property[_]](propertyInt, propertyDouble):_*)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.