ferk86
ferk86

Reputation: 2345

Convert between scala class and Dynamic

  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?

Upvotes: 8

Views: 1251

Answers (1)

sjrd
sjrd

Reputation: 22085

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

Upvotes: 15

Related Questions