Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The reason for the first result is that the <code>getClass</code> method has the following signature in Java</p> <pre><code>public final Class&lt;?&gt; getClass() </code></pre> <p>which Scala inherits. While we know that if we call <code>getClass</code> on an reference of type T the signature could be</p> <pre><code>public final Class&lt;? extends T&gt; getClass() </code></pre> <p>the compiler does not. You could imagine some language extension to provide a special type that represents the static type of the receiver that would enable</p> <pre><code>public final Class&lt;? extends Receiver&gt; getClass() </code></pre> <p>or some sort of special casing in the compiler for <code>getClass</code>. It seems in fact that Snoracle Java indeed special cases <code>getClass</code> but I'm not sure it's required by the Java Language Specification. However, if you have a reference of some particular static type T, there's no reason you couldn't do the equivalent <code>T.class</code> (java) or <code>classOf[T]</code> (scala). In other words such an extension would not bring any greater expressive power but would complicate the implementation of the language.</p> <p>As for the "compile time cast" versus the "'static' cast", there's really no difference there. It would be correct for a compiler to desugar <code>x.asInstanceOf[T]</code> to <code>classOf[T].cast(x)</code>.</p> <p>Any language with subtyping is going to have a possibility that the statically known type of a reference is less specific than the type of the value to which it refers. Languages with static type systems that do not have subtyping usually do not have a concept of runtime types as there is only one actual type that inhabits a given type name. In these languages types are erased at runtime, much the same way that type parameters are erased on the JVM.</p> <p>I hope this helps your understanding of static types of references as compared to runtime type of values.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload