为什么这种转换不会失败?

WIl*_*JBD 5 kotlin

正在测试演员表,列表等的行为,遇到了我不太清楚的东西。将列表转换为不同类型的列表时,不会引发异常,也不会在使用安全转换时导致空值。为什么是这样?

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)
}
Run Code Online (Sandbox Code Playgroud)

输出量

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)]
Run Code Online (Sandbox Code Playgroud)

当我将它们设置为健全性检查时,我还尝试对列表进行深拷贝。

hot*_*key 5

在Kotlin中,有关泛型类型的实际类型参数的信息会在运行时删除,因此无法在强制转换期间检查类型参数。

这就是未经检查的强制转换,也是警告告诉您的内容。您可以进行这种强制转换,但必须通过抑制警告来接受运行时可能存在类型不匹配的情况。

请参阅语言参考:

相关问答: