I have a java function:
public static void initialize(@NonNull Activity activity, Settings... settings) {}
I want to call it from kotlin:
fun initialize(activity: Activity, vararg settings: settings) = JavaClass.initialize(activity, settings)
But it does not compile, telling me that there is type mismatch, Settings
is required, but the argument is kotlin.Array<out Settings>
I see that it's trying to match it with signture
public static void initialize(@NonNull Activity activity, Settings settings) {}
but I want to use
public static void initialize(@NonNull Activity activity, Settings[] settings) {}
Variable number of arguments (varargs)Only one parameter can be marked as vararg . If a vararg parameter is not the last one in the list, values for the subsequent parameters can be passed using named argument syntax, or, if the parameter has a function type, by passing a lambda outside the parentheses.
Kotlin code access Java array We can simply call Java class method which takes array as an argument from Kotlin file. For example, create method sumValue() which takes array element as parameter in Java class MyJava. java calculating addition and returns result. This method is called from Kotlin file MyKotlin.
Kotlin provides the first-class interoperability with Java, and modern IDEs make it even better. In this tutorial, you'll learn how to use both Kotlin and Java sources in the same project in IntelliJ IDEA. To learn how to start a new Kotlin project in IntelliJ IDEA, see Getting started with IntelliJ IDEA.
In Kotlin, You can pass a variable number of arguments to a function by declaring the function with a vararg parameter. a vararg parameter of type T is internally represented as an array of type T ( Array<T> ) inside the function body.
You should use the following syntax:
fun initialize(activity: Activity, vararg settings: settings) = JavaClass.initialize(activity, *settings)
https://kotlinlang.org/docs/reference/java-interop.html#java-varargs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With