问题描述
我有此代码:
// allocate one mesh
pScene.mNumMeshes = 1
pScene.mMeshes = mutableListOf(AiMesh())
val pMesh = pScene.mMeshes[0]
mMeshes
是类型
var mMeshes: MutableList<AiMesh>? = null,
编译器在最后一行抱怨,我尝试在其中声明pMesh
Compilers complains on the last row, where I try to declare pMesh
出什么问题了?
推荐答案
由于mMeshes
是var
属性,因此可以在mutableListOf(AiMesh())
的分配与pScene.mMeshes[0]
中的用法之间进行更改,这意味着不能保证在使用现场不会为空.
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
视为可为空MutableList<AiMesh>?
,并且不允许您将其用作MutableList<AiMesh>
(即,它不能安全地执行智能投射).
The compiler enforces null-safety, treating pScene.mMeshes
as nullable MutableList<AiMesh>?
and not allowing you to use it as MutableList<AiMesh>
(i.e. it cannot safely perform a smart cast).
要解决此问题,您可以简单地创建非空断言:
To fix that, you can simply make a non-null assertion:
val pMesh = pScene.mMeshes!![0]
或者只是重复使用您输入到列表中的值:
Or just reuse the value you put into the list:
val pMesh = AiMesh()
pScene.mMeshes = mutableListOf(mesh)
// use `pMesh` below
这篇关于Kotlin,由于表情复杂,无法进行智能投射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!