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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With