.asInstanceOf
SC-T1000The asInstanceOf
method allows you to explicitly convert an object from one type to another. However, this method should be used with caution. Passing in an invalid type parameter may cause the method to produce unreliable results.
// Produces no error.
val casted = List("a", "b", "c").asInstanceOf[List[Int]]
// Results in `java.lang.ClassCastException`.
println(casted(0))
// Results in an immediate `java.lang.ClassCastException`.
1.asInstanceOf[String]
Although List[String]
is not the same as List[Int]
, the asInstanceOf
method does not throw any Exception
, giving an illusion that the cast operation was successful. However, accessing the casted elements results in a ClassCastException
. This is due to the compiler erasing information about generic types of List
such as Int
and String
in this case.
Note: This rule exists for compatibility reasons for users coming from other 3rd party Scala static analysis tools.