Was testing the behavior of casting, lists, etc. and ran into something that I can not quite figure out. When casting a list into a list that is not of the same type no exception is thrown, nor when using a safe cast does it result in a null. Why is this?
data class Rectangle(val width: Int, val height: Int)
data class Circle(val radius: Int)
fun main(args: Array<String>) {
val listOfRects: List<Rectangle> = listOf(Rectangle(5,5))
val listOfUnkown: List<Any?> = listOfRects
val listOfWrongType: List<Circle> = listOfUnkown as List<Circle>
// also works, thought should throw null
// val listOfWrongType: List<Circle>? = listOfUnkown as? List<Circle>
print(listOfWrongType)
}
Output
Test.kt:9:44: warning: unchecked cast: List<Any?> to List<Circle>
val listA: List<Circle> = listOfUnkown as List<Circle>
^
[Rectangle(width=5, height=5)]
I also tried making deep copy of the lists when I was setting them just as a sanity check.