如果变量不为空,则分配给变量的更简洁方法

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

我在 lambda 函数中有一些代码,如下所示:

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

有没有办法使用 let/with/apply/run 函数来缩短此代码(减少引用 model.time 字段的次数,并尽可能删除临时变量 oldTime )和空安全运算符?

不幸的是,将 model.time ?: return 放在开头不起作用,因为它在 lambda 函数中。

这应该会稍微缩短您的代码:

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
}