Alexei
Alexei

Reputation: 15656

Can't omit default params when call Kotlin's function from Java in Android project

I need to write function (createSend) that has 3 params. But only last (callback) must be required. So to do this I use default (null) value of optional params.

fun createSend(
        amount: Double? = null, currency: String? = null, callback: Callback<Send>
    ) {
}

and here client call (java code in Android project):

TransportService.INSTANCE.createSend(12.1, "USD", new DefaultRestClientCallback<Send>() {
...}

Nice it's work fine.

But now I want to omit first param (amount). I try this:

TransportService.INSTANCE.createSend( "USD", new DefaultRestClientCallback<Send>() {
...
}

and now I get compile error:

                TransportService.INSTANCE.createSend( "USD", new DefaultRestClientCallback<Send>() {
                                         ^
  required: Double,String,Callback<Send>
  found: String,<anonymous DefaultRestClientCallback<Send>>
  reason: actual and formal argument lists differ in length

Upvotes: 1

Views: 960

Answers (1)

findusl
findusl

Reputation: 2644

If you are calling the function from Java code, you need to annotate the function in Kotlin with @JVMOverlads to generate the Java overloads.

@JVMOverloads
fun createSend(
    amount: Double? = null, currency: String? = null, callback: Callback<Send>
) {
}

However this will not work if you still have parameters after the one you leave out. This is common with normal overloads in java as well. Because its not clear which ones you leave out.

Note: Should you try to call the function from Kotlin like this, you can used named parameters to leave out a parameter that is not the last. But java doesn't have that.

Upvotes: 4

Related Questions