简体   繁体   中英

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:

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...) :

// 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?

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 .

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:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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