有人可以解释为什么此代码的输出是true true
,而不是true false
。
我还想知道如何使用true false
获得def apply(in:Any)
的输出。我也尝试了参数化类型,但我仍然得到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 - 通过文章和附件,我发现我可以通过true false
和manifest[T1].erasure.isInstance(t1)
获得manifest[T1].erasure.isInstance(t2)
。
答案 0 :(得分:7)
编译代码时,我得到以下编译器消息:
[warn] there were 1 unchecked warnings; re-run with -unchecked for details
[warn] one warning found
要将-unchecked
传递给编译器,我创建一个包含:
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])
此时,我必须推荐你excellent explanation of type erasure以及如何解决这个问题。