Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call java varargs method from kotlin

Tags:

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) {} 
like image 394
TpoM6oH Avatar asked Apr 14 '16 14:04

TpoM6oH


People also ask

How do you use Varargs in Kotlin?

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.

How do you call a Java class in Kotlin?

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.

Can Kotlin interact with Java?

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.

How does Kotlin define Varargs?

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.


1 Answers

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

like image 74
Michael Avatar answered Oct 27 '22 00:10

Michael