Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The behaviour of casting <code>null</code> to an <code>Int</code> depends on the context in which it is done.</p> <p>First of all, if you cast a <code>null</code> to an <code>Int</code>, it actually means a boxed integer, whose value is <code>null</code>. If you put the expression in a context where the expected type is <code>Any</code> (which is translated to <code>Object</code> behind the scene, because in the JVM bytecode, there is no way to refer to a primitive type and a reference type with the same reference), then this value is not converted further - that is why <code>println(null.asInstanceOf[Int])</code> prints <code>null</code>.</p> <p>However, if you use this same boxed integer value in a context where a primitive <code>Int</code> (Java <code>int</code>) is expected, it will be converted to a primitive, and <code>null</code> is (as a default value for reference types) converted to <code>0</code> (a default value for primitive types).</p> <p>If a generic method does this cast, then, naturally, you get a <code>null</code> back.</p> <p>However, if this method is specialized, then its return type is <code>Int</code> (which is a primitive integer in this case), so the <code>null: Any</code> value has to be converted to a primitive, as before.</p> <p>Hence, running:</p> <pre><code>object Test extends App { println(null.asInstanceOf[Int]) def printit(x: Int) = println(x) printit(null.asInstanceOf[Int]) def nullint[T] = null.asInstanceOf[T] println(nullint[Int]) def nullspecint[@specialized(Int) T] = null.asInstanceOf[T] println(nullspecint[Int]) } </code></pre> <p>produces:</p> <pre><code>null 0 null 0 </code></pre>
 

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