Shorn
Shorn

Reputation: 21554

scala.js - is js.Dictionary the right type for a "Map"

I am using the Twilio Video javascript API with scala.js, for example, the conversations API: https://media.twiliocdn.com/sdk/js/conversations/releases/0.13.9/docs/Conversation.html

The API makes use of javascript "Map" objects (it creates them with javascript code like new Map().)

The only way I've been able to get this to work in my scala.js object is with a js.Dictionary, something like:

@js.native
class TwilioConversation extends js.Object {

  var participants: js.Dictionary[TwilioParticipant] = js.native

Is that the right type to model a "Map", or is there a better one? When I tried using scala Map/mutable.Map, it failed with a class cast exception.

Upvotes: 3

Views: 586

Answers (1)

sjrd
sjrd

Reputation: 22105

It is not exactly the right type. The right type would be js.Map, but at the moment it does not exist yet. It still lives in a work-in-progress PR at https://github.com/scala-js/scala-js/pull/2110/files#diff-4937cb9b8e89d2f21babe311012e63a1

Before it makes it into Scala.js proper, you have two options:

  • Use js.Dictionary as you do, which will work as long as all you need to do is use String keys, and get/set values (because the public API for those operations is the same for a dictionary and a map).
  • Define a JSMap in your codebase, like this: (inspired from the above-linked PR but without references to the Iterable and Iterator parts):
import scala.scalajs.js
import js.annotation._

@js.native
@JSName("Map")
class JSMap[K, V] extends js.Object {
  def size: Int = js.native

  def clear(): Unit = js.native

  def has(key: K): Boolean = js.native

  def get(key: K): js.UndefOr[V] = js.native

  def set(key: K, value: V): this.type = js.native

  def delete(key: K): Boolean = js.native
}

Upvotes: 4

Related Questions