How to invoke method with variant arguments of java?


#1

Hi all,

Now I have such a method in java:

  public static void reload(ClassDefinition... definitions) throws UnmodifiableClassException, ClassNotFoundException {

  instrumentation.redefineClasses(definitions);

  }

and this in kotlin:

fun reload(vararg definitions:ClassDefinition){

  SomeJavaClass.reload(definitions)

}

the kotlin compiler complains  the java method need a parameter of type ClassDefinition , but not Array<ClassDefinition> .

Is this a bug ?

Thanks.

Outersky


#2

Looks like bug.. you can only call function only if you know how many parameters.. also note that this is not Kotlin-Java interoperability issue but any vararg parameter can't be used as argument..

fun t(vararg x : String) {   t2(x) }

fun t2(vararg y : String) {
  println(y.size)
}


This does not work because compiler trying to pass x as first parameter instead of the whole vararg


#3

In Kotlin, you can't pass an array where a vararg parameter is expected. Instead, you have to spread an array:

``

fun reload(vararg definitions:ClassDefinition){

  SomeJavaClass.reload(*definitions)

}

Unfortunately, the back-end does not suport this yet. It’s on the way, though.