Home > Net >  Scalajs, js.Dictionary inconsistent behavior
Scalajs, js.Dictionary inconsistent behavior

Time:11-16

I have an inconsistent error using ScalaJS. Here is a minimal example: the size and the content of a dictionary variable are inconsistent.


def A(mapping: js.Dictionary[String]): Unit = {
  dom.console.log(mapping)
  dom.console.log(mapping.size)
}

I link the IRs using fastOptJS. In the driver code in html, I have

const colorSetting = new Map([
        ["1", "black"]
]);
ScalaJSExample.A(colorSetting)

In the console, the first line prints the content of the variable correctly,

"Map {"1" => "black"}"

but the second line prints 0. I have also tried to swap the position of the two lines, but the result is the same. Any methods such as .foreach or the for (x <- mapping) all treat the variable mapping as empty.

Any suggestion why this is the case? I am using Scala 2.12.8, ScalaJS 1.7.1.

Thanks!

CodePudding user response:

A js.Dictionary represents a POJO (plain old JavaScript object) where elements are fields. But you are passing a JS new Map() to it, which is not a POJO--it's a Map. The correct type to represent a JS Map is js.Map.

Either pass a dictionary to ScalaJSExample.A, as follows:

const colorSetting = {
    "1": "black"
};
ScalaJSExample.A(colorSetting)

or declare mapping as a js.Map in the Scala.js code:

def A(mapping: js.Map[String, String]): Unit = {
  dom.console.log(mapping)
  dom.console.log(mapping.size)
}
  • Related