繁体   English   中英

将Scala`Comparable`数组传递给Java通用方法

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM