如何在Kotlin中将Any转换为List?

3 kotlin

当我尝试投AnyList像在下面的例子中,我得到" Unchecked cast: Any! to List"的警告.有这种问题的解决方法吗?

val x: List<Apples> = objectOfTypeAny as List<Apples>
Run Code Online (Sandbox Code Playgroud)

gue*_*ter 9

这只是一个"警告",说只是为了施放而不是100%安全.更好的选择是:

if (objectOfTypeAny is List<*>) {
        val a: List<Apples> = objectOfTypeAny.filterIsInstance<Apples>()
        ...
}
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅https://kotlinlang.org/docs/reference/typecasts.html.

  • 1.我没有侮辱任何人。2. 我试了一下:`Error:(7, 31) Kotlin: Type mismatch: inferred type is Any but List&lt;Apples&gt; was expected`。自己看:http://rextester.com/ISWQP14284 (2认同)