As a test, I wrote this code:
object Ambig extends App {
def f( x:Int ) { println("Int" ) }
def f( x:String ) { println("String") }
f( null.asInstanceOf[Int ] )
f( null.asInstanceOf[String] )
f(null)
}
I was expecting to get an error on that last invocation of f(), saying that it was ambiguous. The compiler accepted it, and produced this output:
Int
String
String
Now I'm guessing that this has to do with the fact that Int is not an AnyRef, so the only version of f that works for f(null) is f(x:String). But then, if an Int can't be null, what does null.asInstanceOf[Int] mean? The repl says it's of type Int:
scala> :type null.asInstanceOf[Int]
Int
but I don't really see how that works. After all, if I try to cast a String to an Int, all hell breaks loose:
scala> "foo".asInstanceOf[Int]
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
at scala.runtime.BoxesRunTime.unboxToInt(Unknown Source)
...
Of course that's to be expected -- "foo" can't be made into an Int. But neither can null, so why does casting null to an Int work? Presumably boxing in some form, but the type is still Int, which can't be null...
What am I missing?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…