Kotlin,由于表情复杂,无法进行智能投射 [英] Kotlin, smart cast is impossible because of complex expression

查看:207
本文介绍了Kotlin,由于表情复杂,无法进行智能投射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此代码:

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

mMeshes是类型

var mMeshes: MutableList<AiMesh>? = null,

编译器在最后一行抱怨,我尝试在其中声明pMesh

Compilers complains on the last row, where I try to declare pMesh

由于pScene.mMeshes是一个复杂的表达式,因此无法智能地强制转换为MutableList<AiMesh>

Smart cast to MutableList<AiMesh> is impossible because pScene.mMeshes is a complex expression

出什么问题了?

推荐答案

由于mMeshesvar属性,因此可以在mutableListOf(AiMesh())的分配与pScene.mMeshes[0]中的用法之间进行更改,这意味着不能保证在使用现场不会为空.

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.

编译器强制执行 null-safety ,将pScene.mMeshes视为可为空MutableList<AiMesh>?,并且不允许您将其用作MutableList<AiMesh>(即,它不能安全地执行智能投射).

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

这篇关于Kotlin,由于表情复杂,无法进行智能投射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆