我有一个带有变量datePurchased的项目,该项目可以为null。根据购买日期,我会生成一个标签。当我检查datePurchased是否为null时,在else分支中,我仍然必须检查null。它说不可能进行智能转换,因为它是可变属性。

到目前为止,这是我尝试过的方法:

if (datePurchased == null) {
    ""
} else {
    if (datePurchased.isToday()) {//error here
    }
}

    when {
        datePurchased == null    -> {

        }
        datePurchased.isToday() -> {//smart cast bla bla mutable bla bla
        datePurchased?.isToday() -> {//expected Boolean, got Boolean?
        datePurchased?.isToday()?:false -> {//all good, but does not look nice, since datePurchased can't be null here
        }
        else                     -> {

        }
    }

最佳答案

多亏了marstran,我最终得到了这样的解决方案:

        return datePurchased?.let {
            when {
                it.isToday()     -> {
                    "Today"
                }
                it.isYesterday() -> {
                    "Yesterday"
                }
                else             -> {
                    dateFormat.format(it)
                }

            }
        } ?: ""

关于kotlin - Kotlin是否两次检查null,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40652079/

10-10 20:08