In an mpp, I have a function annotated with `@JvmO...
# javascript
h
In an mpp, I have a function annotated with
@JvmOverloads
, usable from java both with and without its single String parameter. I can't make it work in js. The
hello
function in the example here: https://kotlinlang.org/docs/reference/js-to-kotlin-interop.html#jsname-annotation doesn't have
greeting
as an optional parameter. So are optional parameters not possible for a js target (without using the
external
modifier and actually writing the js yourself)?
t
In JS parameters are optional by default.
kotlinJs
will generate some if statements into the single generated
hello
funktion to determine whether the optional parameter is given or not
s
Add a default argument value to make parameter optional:
Copy code
@JsName("hello")
fun hello(greeting: String = "Hello") {
    println("$greeting!")
}
This will be compiled down to:
Copy code
function hello(greeting) {
    if (greeting === void 0)
      greeting = 'Hello';
    println(greeting + '!');
  }
Then you can call it from JS with or without argument:
Copy code
hello();
hello("Привет");
h
Oh yes, I forgot that this is default in js, @thana, so it really should work. I was confused also because I expected the example on the webpage to be like you show it, @Svyatoslav Kuzmich [JB], that really would make more sense. My problem must be somewhere else. I'll post a new question.