Calling java varargs methods


#1

Hi,

I am trying to call java varargs method  from kotlin code. Looks like the compiler accepts there only one parameter rather than a list of parameters or an array. Is this correct? How should I invoke such a method?

I have tried like this:

bean.javaClass.getMethod(“foo”, parameterTypes = Array<Class<Any?>>() )

This results in
Type mismatch: inferred type is kotlin.Array<java.lang.Class<kotlin.Any?>> but java.lang.Class<out kotlin.Any?> was expected

I can write like

bean.javaClass.getMethod(“foo”, javaClass<A>(), javaClass<B>(), javaClass<C>() )

And this works, but what I have to do is to get that method with dynamically generated argument type list.

Thank you,
Laszlo


#2

Forgot to mention, I use kotlin 8.11 with the corresponding IDEA plugin. (are you planning to release plugin updates for the new versions of kotlin? :))


#3

Try to use spread operator(*), like:

bean.javaClass.getMethod("foo", *params)


#4

That was the solution, thank you!


#5

Where did you learn about that? I thought I'd read all the Kotlin docs and I don't remember this. The varargs section in the docs don't seem to mention it either.


#6

I dont remember, maybe from here http://blog.jetbrains.com/kotlin/2012/06/kotlin-m2-candidate/.

P.S. we have issue about it http://youtrack.jetbrains.com/issue/KT-2464. Feel free to vote.


#7

Thanks for mentioning this. Submitted a PR for the docs: https://github.com/JetBrains/kotlin-web-site/pull/68


#8

Is this still the only way?

Java variable arguments invocation supports passing an array in place of listing arguments at compile time. Is this ‘spread’ the same as the java way? Or is there still an extra step? If there’s an extra step, is it possible to optimize the spread operation when there is ‘just one array’?