thetrystero thetrystero - 1 year ago 114
Scala Question

When to use asInstanceOf?

I'm trying out scalajs and am quite confused about how to access DOM elements using the org.scalajs.dom.html package.
By trial and error, I've discovered that some elements need to be cast to certain types using

, but some do not. Is there a general rule as to when and where
needs to be used?

For example, say I have a
element with id
. In order to access the value of the input I need to use

val content = document.getElementById("myinput").asInstanceOf[html.Input].value

But when it comes time to display
in my
of id
, the compiler didn't complain when I did not use
on the

val mydiv = document.getElementById("contentdiv")
mydiv.innerHTML = content

Also, as a bonus is there a central place to find all the possible
arguments and a mapping of them to actual HTML elements?

Answer Source

The signature of getElementById is

def getElementById(id: String): DOMElement

and DOMElement is defined as

trait DOMElement extends js.Object {
  var innerHTML: String = js.native

  def appendChild(child: DOMElement): Unit = js.native

So, whenever you call getElementById you get a DOMElement back and the only operations you can perform on it are innerHTML and appendChild.

That's why your last example works without explicit casting.

But DOMElement is a very generic type. Sometimes you know that getElementById will return - say - an <input> element.

And that's when you can use asInstanceOf to inform the compiler about this extra piece of knowledge you have.

          hey compiler, I KNOW this is going to be an html.Input,
            please let me do my things and explode otherwise.

Needless to say, you need to be careful when using asInstanceOf. If you are wrong, the compiler won't be able to save you from a runtime crash this time.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download