将 String 强制转换为类型Any
时,将不再自动将其视为String
- 为什么?请参见以下示例:
val str = "foo"
val strAsAny = "bar".asInstanceOf[Any]
def f1(x: String) = println(x.toString)
def f2(x: Any) = println(x.toString)
f1(str) // works, type exactly given
f2(str) // works, subtype of Any given
f1(strAsAny) // works not, but strAsAny.isInstanceOf[String] = true !
f2(strAsAny) // works, type exactly given
这让我有点困惑,因为这两个值仍然具有 type String
:
scala> str.isInstanceOf[String]
res4: Boolean = true
scala> strAsAny.isInstanceOf[String]
res5: Boolean = true
我的猜测是,只有“向上”的 interhitance-chain 的类型转换才会自动完成。它是否正确 ?