How to call with optional params in JS interface for Kotlin

688 views Asked by At

I have a Javascript bridge method in Kotlin like,

@JavascriptInterface
fun add(a: Int? = 0, b: Int? = 0): Int {
  return a + b
}

If I want to call with default value, how can I call this method from web app js?

android.add(null, null) // OR
android.add() // OR
android.add(a = 0, b = 0)// OR

Or what?

2

There are 2 answers

2
Roman Art On BEST ANSWER

To use default value of parameter undefined should be passed as an argument. It could be done like this:

android.add() // empty arguments means all of them are undefined so defaults are used
android.add(1) // a == 1, b == undefined so the default value (0) is used
android.add(void 0, 2) // a == undefined and its default (0) is used, b == 2
0
Faisal Ahmed On

You could also use the annotation

@JvmOverloads

This generates overloaded methods in the compiled bytecode for the @JavaScriptInterface.

You can easily then call

android.add()

from JS in order to invoke the default arguments for your method, still keeping your code idiomatic.