作为测试,我写了这段代码:
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)
}
Run Code Online (Sandbox Code Playgroud)
我期望在最后一次调用f()时遇到错误,说这是不明确的.编译器接受了它,并产生了这个输出:
Int
String
String
Run Code Online (Sandbox Code Playgroud)
现在我猜这与Int不是AnyRef这一事实有关,因此f(null)的唯一f版本是f(x:String).但是,如果Int不能为null,则null.asInstanceOf [Int]是什么意思?repl说它是Int类型:
scala> :type null.asInstanceOf[Int]
Int
Run Code Online (Sandbox Code Playgroud)
但我真的不明白它是如何运作的.毕竟,如果我尝试将一个String转换为一个Int,那么所有的地狱都会崩溃:
scala> "foo".asInstanceOf[Int]
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
at scala.runtime.BoxesRunTime.unboxToInt(Unknown Source)
...
Run Code Online (Sandbox Code Playgroud)
当然这是预期的 - "foo"不能成为Int.但是两者都不能为null,那么为什么将int转换为Int工作呢?想必拳击某种形式,但类型仍然是Int,不能为null ...
我错过了什么?
试过这个:
scala> 2.isInstanceOf[AnyVal]
<console>:8: error: type AnyVal cannot be used in a type pattern or isInstanceOf test
2.isInstanceOf[AnyVal]
^
Run Code Online (Sandbox Code Playgroud)
还有这个:
scala> 12312 match {
| case _: AnyVal => true
| case _ => false
| }
<console>:9: error: type AnyVal cannot be used in a type pattern or isInstanceOf test
case _: AnyVal => true
^
Run Code Online (Sandbox Code Playgroud)
这条消息非常有用.我知道我不能使用它,但我该怎么办?
我在想,为什么AnyVal不能用于isInstanceOf检查?这种行为背后的原因是什么?
scala> val c = 't'
c: Char = t
scala> c.isInstanceOf[AnyVal]
<console>:12: error: type AnyVal cannot be used in a type pattern or isInstanceO
f test
c.isInstanceOf[AnyVal]
Run Code Online (Sandbox Code Playgroud)