我试图回答this问题,因为我以为我知道答案。 事实证明,我不知道已经足够:/为什么`.asInstanceOf`有时会抛出,有时不会呢?
下面是测试我做过:
class Inst[T] {
def is(x: Any) = scala.util.Try { as(x) }.isSuccess
def as(x: Any): T = x.asInstanceOf[T]
}
scala> new Inst[String].is(3)
res17: Boolean = true
scala> new Inst[String].as(3)
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
... 33 elided
这到底是怎么回事?为什么只有第二个电话打到as
,而不是第一个电话呢?
没有,这似乎并不以解释很多:我将'is'定义更改为:def is(x:Any)= scala.util.Try {as(x).toString} .isSuccess',并且它仍然返回'true'(即,投不投)。 即使这个'def是(x:Any)= scala.util.Try {println(as(x).toString)} .isSuccess;''愉快地打印出“3”并返回true: -/ – Dima
请参阅我的编辑 –
嗯,现在有道理,谢谢! 'is'不知道'T'是什么,所以它将这个参数视为'Any'。我试过这个:'特质Foo {def foo = ??? } class Inst [T <:Foo] {def is(x:Any)= scala.util.Try {as(x).foo} .isSuccess; def as(x:Any):T = x.asInstanceOf [T]; }'。现在'new Inst [Foo] .is(3)'按预期返回'false'。 – Dima