Cast any to specific array type without warning

IntelliJ gives me a warning on the following:

fun main(args: Array<String>) {
    val foo: Any = arrayOf("test")
    val bar = foo as Array<String>
}

It says it’s an unchecked cast. It does not give me this with Array<*>. I am aware with type erasure on the JVM that this is understandable with most generics, but with arrays even though Kotlin treats the element type as generic, the JVM does not and "(String[]) foo " is perfectly valid.

Is this by intention? How should I mimic a totally normal specific array type cast in Kotlin without getting a warning?

Even if it is possible to check in runtime that array element type is String, an array instance still can contain null elements, therefore foo as Array<String> is still an unchecked cast, because its impossible to ensure nullability of the element type.

That said, it seems possible to make foo as Array<String?> a checked cast, but that is not implemented yet, there’s an issue about this: https://youtrack.jetbrains.com/issue/KT-11948#comment=27-1412659.

1 Like