Haspemulator
Haspemulator

Reputation: 11308

Convert JavaScript`s Number to Scala's Double

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?

Upvotes: 0

Views: 304

Answers (1)

Justin du Coeur
Justin du Coeur

Reputation: 2659

@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]

Upvotes: 2

Related Questions