Search code examples
javascriptandroidkotlinweb-applicationsscripting-bridge

How to call with optional params in JS interface for Kotlin


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?


Solution

  • 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