Search code examples
kotlinnullablemutablekotlin-null-safety

Kotlin check for null twice in if else


I have an item with variable datePurchased, which can be null. Based on purchase date, I generate a label. When I check if datePurchased is null, in else branch I still have to check for null. It says that smart cast is impossible, because it's a mutable property.

Here's what I've tried so far:

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                     -> {

        }
    }

Solution

  • Thanks to marstran, I ended up with such solution:

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