Kotlin, smart cast is impossible because of complex expression

后端 未结 1 1071
春和景丽
春和景丽 2021-01-03 21:06

I have this code:

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

Where <

1条回答
  •  走了就别回头了
    2021-01-03 21:32

    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? and not allowing you to use it as MutableList (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
    

    0 讨论(0)
提交回复
热议问题