2016-04-23 62 views
0

我在图书馆这些类:传斯卡拉`Comparable`阵列到Java泛型方法

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

回答

0

你需要的是改变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):_*) 
+0

我不能更改代码'state'。它来自图书馆。 –

+0

@HenryW。,你可以在你的java代码中创建一个帮助器方法,它需要'Property ...'并返回'Property []'? – Aivean

+0

@HenryW。实际上,没关系,看看更新。 – Aivean