ceran ceran - 1 month ago 8x
Scala Question

Scala.js: object literal with keys having colons in their names

A Javascript library I'm using expects objects like the following one:

"paren:action": ...

As you can see, there is a colon in the name of the key/attribute, which is the reason I have to put the name in quotes.
At the moment, I'm trying to do create an identical object using Scala.js:

def create() = {
literal(`paren:action` = ...)

I'm already using back ticks because without them, it doesn't even compile. However, the name of the resulting object is not as expected.

Example (executed in the Chrome console):

var a = { "paren:action": ... };
"paren:action" in a; // => true
Object.keys(a); // => ["paren:action"]

var b = ScalaJsApp().create();
"paren:action" in b; // => false
Object.keys(b); // => ["paren$colonaction"]

How can I fix this?


The easiest solution to work around this problem is to use a js.Dictionary:

def create() = {
  js.Dictionary("paren:action" -> ...)

This of course should also work with literal but doesn't, due to nasty compiler internal details: paren$colonaction is how the Scala compiler internally represents the name paren:action, mainly due to restrictions on allowed characters in JVM bytecode.