I have this code:
// allocate one mesh pScene.mNumMeshes = 1 pScene.mMeshes = mutableListOf(AiMesh()) val pMesh = pScene.mMeshes[0]
Where mMeshes
is a parameter of type
var mMeshes: MutableList<AiMesh>? = null,
Compilers complains on the last row, where I try to declare pMesh
Smart cast to MutableList<AiMesh>
is impossible because pScene.mMeshes
is a complex expression
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.
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