Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin, smart cast is impossible because of complex expression

Tags:

kotlin

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?

like image 693
elect Avatar asked Nov 15 '16 14:11

elect


1 Answers

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
like image 52
hotkey Avatar answered Nov 03 '22 15:11

hotkey