2016-04-23 15 views
0

Ich habe diese Klassen in der Bibliothek:Passing scala `Comparable` Array Java generische Methode

// 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 */ } 
} 

und es gibt eine Methode, die eine Liste von Property s nimmt, die ich verwenden möchte:

public void state(Property... properties) { 
    /* some code */ 
} 

Ich kann das Obige nicht ändern, da sie aus einer Bibliothek stammen. In scala, ich den folgenden Code haben, die ein Array void state(Property...) zu passieren versucht:

// This is scala 
val propertyInt = PropertyInt.create("index") 
val propertyDouble = PropertyDouble.create("coeff") 
state(Array[Property](proeprtyInt, propertyDouble))) 

Die letzte Zeile des Codes einen Fehler hat: Type mismatch, expected Property[_ <: Comparable[T]], actual Array[Property] Wie kann ich dieses Problem beheben?

Hinweis: Dies ist eine vereinfachte Version eines komplizierteren Codes. Im realen Code implementiert Property<T extends Comparable<T>> die Schnittstelle IProperty<T extends Comparable<T>> und IProperty wird als Argumente für state genommen.

Edit: Die folgende

val properties = Array(propertyInt.asInstanceOf[IProperty[_ <: Comparable[_]]], 
        propertyDouble.asInstanceOf[IProperty[_ <: Comparable[_]]]) 
state(properties) 

Gibt dem Fehler

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

Antwort

0

Was Sie brauchen, ist die state Argumente zu ändern generisch sein:

public static void state(Property<?> ... properties) { 
    /* some code */ 
} 

Dann können Sie tun:

// This is scala 
val propertyInt = PropertyInt.create("index") 
val propertyDouble = PropertyDouble.create("coeff") 

state(propertyInt, propertyDouble) 

state(Array(propertyInt, propertyDouble):_*) 

Upd, wenn Sie nicht die Unterschrift des state ändern können, können Sie es immer noch wie folgt aufrufen:

state(Array[Property[_]](propertyInt, propertyDouble):_*) 
+0

ich nicht den Code für 'state' ändern können. Es stammt aus einer Bibliothek. –

+0

@HenryW., Können Sie eine Hilfsmethode in Ihrem Java-Code erstellen, die 'Property ...' übernimmt und 'Property []' zurückgibt? – Aivean

+0

@HenryW., Eigentlich egal, siehe das Update. – Aivean