Kotlin, smart cast is impossible because of complex expression

匿名 (未验证) 提交于 2019-12-03 00:52:01

问题:

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?

回答1:

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 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!