0

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?

Joshua
  • 2,932
  • 2
  • 24
  • 40
  • You should clearly state the question you want answered. Are you asking if this is a bug? Are you asking why this design decision was made? Are you asking how you can achieve the same behavior? – Joey Harwood Mar 01 '18 at 14:38
  • I could not reproduce this behavior. It seems like this is allowed for `Object... args` to pass `null` as an item – in my test project it worked just fine. Is `execute`, `args` or the enclosing class marked by some nullability annotation? Does `execute` perform any checks inside? What is the stacktrace of your `IllegalStateException` – is it thrown in Kotlin code or inside `execute`? – hotkey Mar 01 '18 at 14:44
  • Thank you for trying to reproduce the behaviour. Neither of `execute`, `args` or the class are marked by any annotation. `args` is null checked by a helper method called by `execute`. The stack trace says `java.lang.IllegalStateException: javaObject.execute(... args) must not be null at kotlinclass.kotlinfunction` – Joshua Mar 01 '18 at 14:48
  • This exception 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. – yole Mar 01 '18 at 14:49
  • Gosh, thanks @yole. If you post it as an answer, I'll accept it – Joshua Mar 01 '18 at 14:49

1 Answers1

2

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.

yole
  • 92,896
  • 20
  • 260
  • 197