在Kotlin中将Any转换为Array [英] Cast Any to Array in Kotlin

查看:1602
本文介绍了在Kotlin中将Any转换为Array的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过从Kotlin中的Map<String, Any>加载数据来初始化类.由于此Map是直接从JSON收集的,因此我不确定是否存在任何给定的键,或者它的值是否属于我期望的类型.为了安全地解开此地图的包装,我正在执行以下操作,该方法似乎运行良好:

I'm initializing a class by loading data from a Map<String, Any> in Kotlin. As this Map is gleaned directly from JSON, I don't know for certain that any given key exists, or that its value is of the type I expect. To unpack this Map safely I'm doing the following, which appears to work perfectly:

a = rawData["A"] as? String ?: ""

其中一些数据位于进一步嵌套的JSON中,我正在将其解压缩到Arrays中;我尝试以相同的方式执行此操作:

Some of this data is in further nested JSON, which I'm unpacking to Arrays; I've tried to do this in the same way:

b = rawData["B"] as? Array<String> ?: arrayOf<String>()

但是,当我尝试使用数组(如上所述)进行操作时,IntelliJ大惊小怪,说

However, when I attempt this using an array (as above) IntelliJ kicks up a fuss, saying

警告:(111,30)Kotlin:未经检查的演员表:有吗?数组< String>

Warning:(111, 30) Kotlin: Unchecked cast: Any? to Array<String>

这仅仅是让IDE陷入困境吗?还是这种方法对Arrays来说确实不安全,尽管对于其他类型似乎完全安全?

Is this just the IDE getting itself in a twist or is this method genuinely unsafe for Arrays despite being seemingly perfectly safe for other types?

推荐答案

我准备将其称为bug,因为Array是一种经过验证的类型,这意味着它的泛型参数实际上可以在运行时进行检查(不同于,例如).我尝试查看它是否已归档,事实证明编译器实际上是向您显示警告的正确方法.正如您在对此问题的回复中看到的那样,演员表仍然存在可空性问题这种.

I was ready to call this a bug, because Array is a reified type, meaning its generic parameter can actually be checked at runtime (unlike a List, for example). I've tried looking to see if it's been filed yet, and it turns out the compiler is actually right to show you a warning. As you can see in the response to this issue, there's still a nullability problem with casts of this kind.

val a = arrayOf("foo", "bar", null) as Array<String>
println(a[2].length)

类似于本示例中的数组的数组已成功转换(使用as,它们不引发异常,使用as?,它们不返回null),但是,强制转换不能确保这是一个Array<String>,只是它是一个Array<String?>.

Arrays like the one in this example are successfully cast (using as, they don't throw an exception, using as?, they don't return null), however, the cast can not ensure that this is an Array<String>, only that it's an Array<String?>.

这意味着您以后可以在强制转换后从键入为Array<String>的变量中读取null值,而无需编译器的进一步警告.

This means that you can later read null values from a variable that is typed as an Array<String> after the cast, with no further warnings from the compiler.

这篇关于在Kotlin中将Any转换为Array的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆