Search code examples
kotlinkotlin-interop

Passing null as part of vararg parameter to Java method from Kotlin


I have something similar to this method declaration in Java. Let's say the class is named JavaClass:

public T execute(String s, Function<T> f, Object... args) {}

If I want to call this from Kotlin (my version is 1.2.21), I could write something similar to this:

val arg1 = ""
val arg2: String? = null
val javaObject = JavaClass()

javaObject.execute("some string", { print(it) }, arg1, arg2)

The strange thing is that I get an IllegalStateException when executing this code. It says arg2 must not be null. I could understand if it said that args must not be null. But considering that this call would result in the array looking like ["", null], which in Java is perfectly fine, this seems very strange.

I need to be able to pass null values to this method. What do I need to do to fix this behaviour?


Solution

  • The IllegalStateException thrown for such a call means that the method has returned null and you're assigning the return value to a variable of a non-null type. It has nothing to do with varargs.