gpt4 book ai didi

android - 寻找Android应用程式中Kotlin非空断言错误的解释吗?

转载 作者:行者123 更新时间:2023-12-02 13:18:31 24 4
gpt4 key购买 nike

我是Kotlin的新手,正在编写一个Android应用程序,但收到以下屏幕快照中所示的编译器警告。

关于这个特定错误的问题与以下几行有关:

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

具有==的第一行编译正常,但> 1会生成空断言。我添加了该错误的屏幕截图和代码段。顺便说一句,如果有更好的编码方法,这可能会对我对问题的理解有所帮助。

如果我加了!!如错误中所述,它会编译并运行,但是如果months var为null,则可能是应用程序崩溃了。

我不太明白为什么==与>不同

enter image description here

我从中获取此数据的数据库将“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

您可以在此处阅读有关运算符重载的更多信息:https://kotlinlang.org/docs/reference/operator-overloading.html

关于android - 寻找Android应用程式中Kotlin非空断言错误的解释吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61370221/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com