Work with opaque types (Char and Long)

I am trying to export a Scala implementation of an algorithm for use in JavaScript. I am using @JSExport . The algorithm works with Scala Char and Long values, which are marked as opaque in the compatibility guide .

I would like to know (a) what this means; and (b) a recommendation to solve this problem.

I guess this means that I should avoid Char and Long and work with String plus runtime checking (or perhaps use the shapeless Sized collection) and Int .

But other ideas are welcome.

More details ...

The kind of code I'm looking for is:

 @JSExport("Foo") class Foo(val x: Int) { @JSExport("add") def add(n: Int): Int = x+n } 

... which works as expected: new Foo(1).add(2) produces 3 .

Replacing Long types with the same call reports: java.lang.ClassCastException: 1 is not an instance of scala.scalajs.runtime.RuntimeLong (and something similar with methods that accept and return Char ).

+5
source share
1 answer

Being opaque means that

  • No matching javascript type
  • It is not possible to create a value of this type from JavaScript (except if the @JSExport ed constructor @JSExport )
  • It is not possible to manipulate a value of this type (except for calls to @JSExport ed methods and fields)

You can still get the value of this type from Scala.js code, pass it and return it to Scala.js code. You can also always call .toString() , because java.lang.Object.toString() is @JSExport ed. Other than toString() , neither Char nor Long export anything, so you cannot do anything with them.

Therefore, as you have already seen, JavaScript 1 cannot be used as Scala.js Long , because it does not have the right type. Also 'a' valid Char (but it is a valid String ).

Therefore, as you yourself assumed, you really should avoid opaque types and use other types instead if you need to create / manipulate them from JavaScript. The Scala.js side can convert back and forth using standard language tools such as someChar.toInt and someInt.toChar .

The choice of which type is best depends on your application. For Char it can be Int or String . For Long it could be a String , a pair of Int s, or perhaps even Double , if the possible values ​​never use more than 52 bits of precision.

+8
source

Source: https://habr.com/ru/post/1210565/


All Articles