- How do you convert from a scala class to Dynamic, so unmentioned javascript functions can be called?
- How do you convert from Dynamic to a scala class?
Asked
Active
Viewed 1,234 times
1 Answers
15
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

sjrd
- 21,805
- 2
- 61
- 91
-
Thanks for the comprehensive explanation. The conversions work. – ferk86 Nov 16 '14 at 16:30