为什么 android studio 即使在 Kotlin 中添加了安全性之后仍需要添加非 null Asserted(!!) 调用

why android studio required to Add non null Asserted(!!) call even after safety is added in Kotlin

it 表示图像中的对象列表。 这里的检查列表不是空的。但显示添加 (?) 安全错误。 但再次显示错误以添加非空断言(!!)甚至添加安全性。
错误只能在添加后才能修复。

 if (it?.isNotEmpty()!!) {
    //do your work here
 }

为什么 android 工作室需要添加非空断言 (!!) 调用。

您的 it 可以为 null(因此它后面的 ?)。因此,用简单的英语来说,该语句就变成了 "if it is not null, is it not empty?",这是一个布尔值。但是,如果 it 为空怎么办?

您对 it?.isNotEmpty() 的评估产生了 Boolean?,它在 if 中不被接受。

因此,一种可能的解决方案是说 "I know it won't be null at that time",然后替换为 it!!.isNotEmpty()

另一种选择是进一步分解您的 if 语句,例如:

if (it != null && it.isNotEmpty())

你可以这样查看

if (it?.isNotEmpty()==true) {
    //do your work here
}