Search code examples
kotlinkotlin-null-safety

Cleaner way to assign to a variable if it's not null


I have some code inside a lambda function like this:

{ y, m, d ->
    // update time, but only if it has already been set
    val oldTime = model.time
    if (oldTime != null) {
        model.time = Calendar.getInstance().apply {
        time = oldTime
        set(Calendar.YEAR, y)
        set(Calendar.MONTH, m)
        set(Calendar.DAY_OF_MONTH, d)
        }.time
    }
}

Is there a way to shorten this code (reduce number of times the model.time field is referenced, and remove the temporary variable oldTime if possible) with the let/with/apply/run functions and null safe operators?

Unfortunately putting model.time ?: return at the start doesn't work since it's inside a lambda function.


Solution

  • This should shorten your code a little bit:

    model.time?.let {
        model.time = Calendar.getInstance().apply {
            time = it
            set(Calendar.YEAR, y)
            set(Calendar.MONTH, m)
            set(Calendar.DAY_OF_MONTH, d)
        }.time
    }