0

I have a kotlin code/library that will end up being used in Java, one of the methods there is:

@JvmOverloads
fun sample(
    param1: ByteArray,
    param2: ByteArray = byteArrayOf(),
    param3: ByteArray = customMethod()
): ByteArray { ... }

Since the method is overloaded (@JvmOverloads), how do I use it in java with only sample(param1, param3), excluding param2?

Java detects the second parameter in sample(param1, param3) as param2, rather than param3 considering that they are of the same data type.

Do I really have to resort to nulls or perhaps an empty byte[] just to skip over the part?

I have tried:

  • Resorting to nulls and do checks based on that, so now I have sample(param1, null, param2);.
  • Using empty byte[] to skip over the part, so now I have sample(param1, byte[], param2);.

But, I want/prefer to have param2 undefined/skipped rather than being defined at all.

What I have researched (but haven't tried)

Joshua Hero
  • 105
  • 5

1 Answers1

4

Since the method is overloaded (@JvmOverloads), how do I use it in java with only sample(param1, param3), excluding param2?

You can't. @JvmOverloads only generates overloads with parameters from first to last. So you can call with param1 and param2, but not with param1 and param3.

You could swap the order of parameters around, but that only works if you don't also need the param 1 & 2 version somewhere else. Or, you could manually add an overload that only takes 1 & 3 and call that from java:

fun sample2(param1: ByteArray, param3: ByteArray) = sample(param1, param3 = param3)

This one should have a different name (or you could confuse with with the param 1 & 2 version), and it doesn't need the default for param3 (because just use the original method).

Jorn
  • 20,612
  • 18
  • 79
  • 126