Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert between scala class and Dynamic

Tags:

scala.js

  1. How do you convert from a scala class to Dynamic, so unmentioned javascript functions can be called?
  2. How do you convert from Dynamic to a scala class?
like image 516
ferk86 Avatar asked Nov 16 '14 15:11

ferk86


1 Answers

If by Scala class you mean a typed facade to JavaScript classes, i.e., a class/trait that extends js.Object, then you can convert simply with an asInstanceOf. For example:

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

The other direction is the same:

val dateStaticAgain = dateDynamic.asInstanceOf[js.Date]

.asInstanceOf[T] is always a no-op (i.e., a hard cast) when T extends js.Any.

If, however, by Scala class you mean a proper Scala class (that is not a subtype of js.Object), then basically you can do the same thing. 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
like image 158
sjrd Avatar answered Sep 18 '22 06:09

sjrd