33

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?

elect
  • 6,765
  • 10
  • 53
  • 119
  • 2
    Does `val pMesh = pScene.mMeshes!![0]` work? If it does, it's because of `mMeshes` being `var` (not guaranteed to be not-null after the assignment). – hotkey Nov 15 '16 at 14:48
  • Oh god, yes, I didn't think about it.. if you answer I'll accept it, thanks! – elect Nov 15 '16 at 14:51

1 Answers1

41

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
hotkey
  • 140,743
  • 39
  • 371
  • 326