希望对Android应用中的Kotlin非空断言错误进行解释。

将相本无种,男儿当自强。这篇文章主要讲述希望对Android应用中的Kotlin非空断言错误进行解释。相关的知识,希望能为你提供帮助。
我是Kotlin的新手,我正在编写一个android应用程序,但我收到了以下截图中描述的编译器警告。
我对这个特殊错误的疑问与以下几行有关。

if (months?.toInt() == 1) { monthsText = "1 Mo " } if (months?.toInt() > 1) { monthsText = String.format("%d Mos ", months) }

第一行的==编译正常,但> 1产生了null断言。 我已经添加了一个错误的截图和一个代码片段。 另外,如果有更好的代码方法,可能对我理解这个问题有帮助。
如果我添加了错误中提到的 !!,它就会编译和运行,但如果月份变量为空,这可能是应用程序崩溃。
我真的不明白为什么==会和& gt不同。
希望对Android应用中的Kotlin非空断言错误进行解释。

文章图片

我从数据库中获取的数据中,"yearsMonthsExperience "存储为 "1205"(YYMM)。
val yearsMonths= (markerData.mMarkerUser!!["yearsMonthsExperience"] as? String)?.padStart(4, '0') val years = yearsMonths?.take(2)?.toInt() val months = yearsMonths?.takeLast(2)?.toInt() var yearsText = "" if (years != null & & years == 1) { yearsText = "1 Yr " } if (years != null & & years > 1) { yearsText = String.format("%d Yrs ", years) } var monthsText = "" if (months?.toInt() == 1) { monthsText = "1 Mo " } if (months?.toInt() > 1) { monthsText = String.format("%d Mos ", months) } mInfoView.lbYearsExperience.text = String.format("%s%s Exp.", yearsText, monthsText)

先谢谢你的解释或帮助。
答案> 是一个被覆盖的操作符。它只是一个语法糖。
所以你的if语句实际上是这样的。months?.toInt().compareTo(1)
为了让它工作,你需要给它一个默认值,就像这样: months?.toInt()?:0 > 1.
【希望对Android应用中的Kotlin非空断言错误进行解释。】你可以在这里阅读更多关于操作符重载的内容。https:/kotlinlang.orgdocsreferenceoperator-overloading.html。

    推荐阅读