0

How to convert an instance of untyped js.Dynamic, which I know is a JavaScript number, to a Scala Double type?

Background: I have a js library that doesn't have a Scala.js wrapper around it (yet). It sends certain events, and I want to use those events' data in Scala code, where I need proper typing.

What I've done so far is the following: first js number to Scala's String, and the String to Double.

map.addListener("click", {(e: js.Dynamic) => {
      val c = map.pixelToGeo(e.displayX, e.displayY)
      GenerateSampleData.mapClickCoord() = 
        Coordinate(
          String.valueOf(c.latitude).toDouble,
          String.valueOf(c.longitude).toDouble)
    }})

It works, but I think it looks ugly, and there must be a better way. Any ideas?

Haspemulator
  • 11,050
  • 9
  • 49
  • 76

1 Answers1

2

@sjrd will correct me if I'm wrong, but I believe that Scala's Double is a JS Number under the hood. So if you're confident that c.latitude is a Number, I believe you can simply say:

c.latitude.asInstanceOf[Double]
Justin du Coeur
  • 2,699
  • 1
  • 14
  • 19
  • You're right. It works, and noticeably faster than my original version. With my approach, I was really able to see delays between clicks on the map and values changing with my naked eye. Not with this approach. I'll postpone accepting this answer, though, maybe other ideas will come up. – Haspemulator Jan 05 '16 at 16:21