thetrystero thetrystero - 26 days ago 17
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

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

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

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


But when it comes time to display
content
in my
div
of id
contentdiv
, the compiler didn't complain when I did not use
asInstanceOf
on the
div
element:

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


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

Answer

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.

document.getElementById("myinput").asInstanceOf[html.Input].value
                                      ^
                                      |
          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.