I have this code:

// allocate one mesh
pScene.mNumMeshes = 1
pScene.mMeshes = mutableListOf(AiMesh())
val pMesh = pScene.mMeshes[0]

其中mMeshes是类型为的参数

var mMeshes: MutableList<AiMesh>? = null,

Compilers complains on the last row, where I try to declare pMesh

智能转换为MutableList<AiMesh>是不可能的,因为pScene.mMeshes是一个复杂的表达式

What's the problem?

推荐答案

Since mMeshes is a var property, it can change between the assignment of mutableListOf(AiMesh()) and the usage in pScene.mMeshes[0], meaning that it is not guaranteed to be not-null at the use site.

编译器强制执行null-safety,将pScene.mMeshes视为可为null的MutableList<AiMesh>?,不允许将其用作MutableList<AiMesh>(即,它不能安全地执行smart cast).

To fix that, you can simply make a non-null assertion:

val pMesh = pScene.mMeshes!![0]

或者只重用您放入列表中的值:

val pMesh = AiMesh()
pScene.mMeshes = mutableListOf(mesh)
// use `pMesh` below

Kotlin相关问答推荐

如何确保Kotlin子类已完成初始化?

从 Kotlin 的父类获取函数注解

如何将消费者放入 Kotlin 的 map 中?

如何使用子变量在 Kotlin 中初始化父级

顶级属性的初始化

为什么 KFunction2 在 Kotlin 中不是可表示类型?

Kotlin 条件格式字符串

这是什么 Kotlin 类型:(String..String?)

无法删除部分子项.这可能是因为进程打开了文件或将其工作目录设置在目标目录中

使用最新的 com.jakewharton.rxbinding3:rxbinding:3.0.0-alpha2 库时未找到 RxTextView 和其他小部件

Kotlin 单元测试 - 如何模拟 Companion 对象的组件?

RecyclerView SnapHelper无法显示第一个/最后一个元素

Kotlin val difference getter override vs assignment

Android EditText 协程go 抖操作符,如 RxJava

在 Kotlin 中创建 Spinner 时,如何在 Fragment 中的旋转屏幕上修复指定为非空的参数为空?

Kotlin:具有多个不同类型设置器的单个属性

将 Double 转换为 ByteArray 或 Array Kotlin

如何将vararg作为数组传递给Kotlin中的函数?

Android studio 4.0 新更新版本说 Kotlin 与这个新版本不兼容

带有注释为@RegisterExtension的字段的 JUnit 5 测试在 Kotlin 中不起作用