Js() function not support spread operator?

Inlined JavaScript code inside the js() function doesn’t seem to support the JavaScript spread operator. Is there some reason behind this?

For example:

val stringFunction: ( String, String, String ) -> Unit = {
    strOne, strTwo, strThree -> console.log( strOne, strTwo, strThree )
}

val stringArray = arrayOf( "one", "two", "three" )

js( "stringFunction( stringArray[0], stringArray[1], stringArray[2] )" ) // logs "one two three"

js( "stringFunction( ...stringArray )" ) // doesn't compile: JavaScript: syntax error

spread operator is es6. Kotlin by default targets es5. If you set the compiler options to es6 does it compile?

1 Like

Yes good shout that must be the reason, thank you.

In the relevant Gradle plugin options it has this snippet:

/**
 * Generate JS files for specific ECMA version
 * Possible values: "v5"
 * Default value: "v5"
 */
var target: kotlin.String

And sure enough putting in “v6” gives an error. So not yet for the spread operator by the looks.

Hi there

It don’t know if ES6 is even supported at the moment as there currently is a PR to support ES6 classes in kotlin : [JS BE] ES6-classes by tihonovcore · Pull Request #3338 · JetBrains/kotlin · GitHub

maybe after this feature the target = 'v6' option would work?

Ah good spot! Looks like it’s somewhere in the pipeline. Although I note it’s Kotlin I’m intending to write, not JavaScript if I can help it :slight_smile:

From what I am understanding this PR is able to lower Kotlin class into JS ES6 class.

I think the webpack configuration used by the kotlin compiler is set to ES5, that’s why the spread operator is unrecognized. If they support ES6 classes, they will probably update said webpack config to ES6, thus supporting spread operator.

Again, this is pure speculation, If someone at jetbrains can enlighten us, it would be great

In code passed to js function you can’t use features introduced after EcmaScript 5. So, you can’t use spread operator there since it was introduced in ES6 (aka ES2015).

Honestly, we don’t recommend to use js function unless you need to do some low-level stuff (for something impossible to implement in pure Kotlin, more rarely for a performance reason).

Right in this case you can write something like:

stringFunction.asDynamic().apply(null, stringArray)

BTW, could you please explain you do you want to use js function?

I was trying to do some simple reflection to make up for the lack of it in Kotlin/JS.

Hello @bashor (or anyone who can help) , how about destructuring props into a component in React? How would you go about that in kotlin?

For example in react, we pass all the props into a component using the spread operator. As in:

<Component {... props} />

Tried using the js() function for this too, but compilation error.

1 Like