Whether it is the only way to convert 'nullable case vararg parameter' from java to Kotlin replace with Array<Some>?

Whether it is the only way to convert ‘nullable case vararg parameter’ from java to Kotlin replace with Array? .

In Java:

void inStream(int eventType, @Nullable String action, StamperNote... notes);

Whether it is the only way to match the same function in Java use Kotlin:

fun inStream(eventType: Int, action: String?, notes: Array<StamperNote>? = null)

If so, why the IDEA Gradle plugin convert it from Java to Kotlin with vararg syntax, what don’t match the same thing I want in Java.

The way to match the same signature in Kotlin is to use a vararg parameter: fun inStream(eventType: Int, action: String?, vararg notes: StamperNote). Your conversion requires the caller to wrap the arguments into an array explicitly.

Note that vararg parameters are, as a rule, never nullable, because in Java there is no good way to distinguish between passing null as the entire vararg array versus passing null as a single element of a non-null vararg array.

2 Likes

Thanks! got it.

vararg parameters are, as a rule, never nullable, because in Java there is no good way to distinguish between passing null as the entire vararg array versus passing null as a single element of a non-null vararg array.

It might not be a good way, but Java does have a way of handling this ambiguity. It’s described in section 15.12.2 of the JLS, and a null parameter is even given as an example. In the “first phase” described there, it treats vararg parameters as if they were declared as arrays. If a matching overload resolution is found in this phase, then that’s what’s used and the parameter is passed as the array, not as an array element. They did it this way so that APIs that used arrays in 1.4 could change to use varargs in 1.5 without breaking existing client code.

So if you have a method like this…

static void foo(Object... x) {
    System.out.println(x == null);
}

…and call it as foo(null) from Java, it’ll print “true”. If you need to pass an array containing a single null, rather than a null array reference, you can do something like foo(new Object[]{null}).

Is there really no way to pass null (rather than an array containing null) to such a method from Kotlin?