当使用.isInstanceOf[GenericType[SomeOtherType]]
, whereGenericType
和SomeOtherType
是任意类型(合适的类型)时,由于类型擦除,Scala 编译器会给出未经检查的警告:
scala> Some(123).isInstanceOf[Option[Int]]
<console>:8: warning: non variable type-argument Int in type Option[Int] is unchecked since it is eliminated by erasure
Some(123).isInstanceOf[Option[Int]]
^
res0: Boolean = true
scala> Some(123).isInstanceOf[Option[String]]
<console>:8: warning: non variable type-argument String in type Option[String] is unchecked since it is eliminated by erasure
Some(123).isInstanceOf[Option[String]]
^
res1: Boolean = true
但是,如果SomeOtherType
它本身是泛型类型(例如List[String]
),则不会发出警告:
scala> Some(123).isInstanceOf[Option[List[String]]]
res2: Boolean = true
scala> Some(123).isInstanceOf[Option[Option[Int]]]
res3: Boolean = true
scala> Some(123).isInstanceOf[Option[List[Int => String]]]
res4: Boolean = true
scala> Some(123).isInstanceOf[Option[(String, Double)]]
res5: Boolean = true
scala> Some(123).isInstanceOf[Option[String => Double]]
res6: Boolean = true
(回想一下元组和是泛型类型=>
的语法糖)Tuple2[]
Function2[]
为什么没有发出警告?(所有这些都在 Scala REPL 2.9.1 中,带有-unchecked
选项。)