我試圖回答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