Convert between scala class and dynamic

  • How do you convert from a scala class to Dynamic, so-called javascript functions can be called?
  • How do you convert from Dynamic to a scala class?
+7
source share
1 answer

If in the Scala class you mean a typed facade for JavaScript classes, i.e. the class / attribute that extends js.Object , then you can convert simply with asInstanceOf . For example:

 val dateStatic = new js.Date val dateDynamic = dateStatic.asInstanceOf[js.Dynamic] 

Other direction:

 val dateStaticAgain = dateDynamic.asInstanceOf[js.Date] 

.asInstanceOf[T] always no-op (ie, hard cast) when T continues js.Any .

If, however, with the Scala class, you mean the correct Scala class (which is not a subtype of js.Object ), then basically you can do the same. But only @JSExport 'ed members will be visible from the js.Dynamic interface. For example:

 class Foo(val x: Int) { def bar(): Int = x*2 @JSExport def foobar(): Int = x+4 } val foo = new Foo(5) val fooDynamic = foo.asInstanceOf[js.Dynamic] println(fooDynamic.foobar()) // OK, prints 9 println(fooDynamic.bar()) // TypeError at runtime 
+12
source share

All Articles