[英]Passing scala `Comparable` array to java generic method
I have these classes in the library: 我的图书馆里有这些课:
// 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 */ }
}
and there is a method that takes a list of Property
s that I want to use: 并且有一个方法接受我要使用的
Property
列表:
public void state(Property... properties) {
/* some code */
}
I cannot change the above since they are from a library. 我无法更改上述内容,因为它们来自图书馆。 In scala, I have the following code which attempts to pass an array to
void state(Property...)
: 在scala中,我有以下代码尝试将数组传递给
void state(Property...)
:
// This is scala
val propertyInt = PropertyInt.create("index")
val propertyDouble = PropertyDouble.create("coeff")
state(Array[Property](proeprtyInt, propertyDouble)))
The last line of code has an error: Type mismatch, expected Property[_ <: Comparable[T]], actual Array[Property]
How do I fix this? 代码的最后一行有一个错误:
Type mismatch, expected Property[_ <: Comparable[T]], actual Array[Property]
如何解决此问题?
Note: This is a simplified version of some more complicated code. 注意:这是一些更复杂的代码的简化版本。 In the real code,
Property<T extends Comparable<T>>
implements the interface IProperty<T extends Comparable<T>>
and IProperty
is taken as the arguments for state
. 在实际代码中,
Property<T extends Comparable<T>>
实现了接口IProperty<T extends Comparable<T>>
并且IProperty
被用作state
的参数。
Edit: The following 编辑:以下
val properties = Array(propertyInt.asInstanceOf[IProperty[_ <: Comparable[_]]],
propertyDouble.asInstanceOf[IProperty[_ <: Comparable[_]]])
state(properties)
Gives the error 给出错误
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)
^
What you need is to change the state
arguments to be generic: 您需要将
state
参数更改为通用:
public static void state(Property<?> ... properties) {
/* some code */
}
Then you can do: 然后,您可以执行以下操作:
// This is scala
val propertyInt = PropertyInt.create("index")
val propertyDouble = PropertyDouble.create("coeff")
state(propertyInt, propertyDouble)
state(Array(propertyInt, propertyDouble):_*)
Upd if you can't change the signature of state
, you can still call it like this: UPD如果你不能改变的签名
state
,你仍然可以调用它像这样:
state(Array[Property[_]](propertyInt, propertyDouble):_*)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.