首页 > 解决方案 > 如何在 Kotlin 的 JS 接口中使用可选参数调用

问题描述

我在 Kotlin 中有一个 Javascript 桥接方法,例如,

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

如果我想使用默认值调用,如何从 web 应用程序 js 调用此方法?

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

要不然是啥?

标签: javascriptandroidkotlinweb-applicationsscripting-bridge

解决方案


要使用参数的默认值,undefined应作为参数传递。可以这样做:

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

推荐阅读