2012-03-10 33 views
1

有人可以解釋爲什麼此代碼的輸出是true true而不是true falseScala:爲isInstanceOf忽略通用抽象類型

我也想知道如何使用def apply(in:Any)實現輸出爲true false。我也嘗試過參數化類型,但我仍然得到true true而不是true false

object TestClass extends App { 

    val xTrue = TypeXObject(TypeX("s")) 
    val xFalse = TypeXObject(TypeY(1)) 
} 

case class TypeX(string:String) 

case class TypeY(int:Int) 

object TypeXObject extends HasAbstractType{override type T = TypeX} 

object TypeYObject extends HasAbstractType{override type T = TypeY} 

abstract class HasAbstractType { 
    type T 
    def apply(in:Any):Any = { 
    println(in.isInstanceOf[T]) 
    in 
    } 
} 

答:

issues.scala-lang.org/browse/SI-5042 - 隨着文章和所附的文章中,我發現,我可以manifest[T1].erasure.isInstance(t1)manifest[T1].erasure.isInstance(t2)得到true false

回答

7

當我編譯代碼我得到以下編譯器消息:

[warn] there were 1 unchecked warnings; re-run with -unchecked for details 
[warn] one warning found 

要通過-unchecked編譯器,我創建一個包含build.sbt:

scalacOptions ++= Seq("-unchecked", "-deprecated") // (I threw in deprecated for good measure) 

後來,當我編譯,我得到這個啓發性的警告:

[warn] /home/lwickland/f/f.scala:18: abstract type HasAbstractType.this.T in type HasAbstractType.this.T is unchecked since it is eliminated by erasure 
[warn]  println(in.isInstanceOf[T]) 

而在那一點上,我有o將您引導至excellent explanation of type erasure以及如何避開它。

+1

https://issues.scala-lang.org/browse/SI-5042 - 你的文章和這篇文章我發現我可以通過manifest [T1] .erasure.isInstance(t1)獲得'true false' '和'manifest [T1] .erasure.isInstance(t2)'。謝謝您的幫助 – George 2012-03-10 15:46:47