【发布时间】:2020-06-07 10:54:20
【问题描述】:
我遇到了一个奇怪的错误,但我无法弄清楚它为什么会发生。如果我调用我的原始函数,roundToMidnight() 不会被调用并且日期不会四舍五入。
我原来的功能,什么不起作用:
suspend operator fun invoke(reference: Reference) = reference.tagId
?.let { tagRepository.getTag(it) }
?.uploadDate ?: Date()
.apply { time += accountRepository.getAccount().first().defaultExpiryPeriod }
.roundToMidnight()
}
有什么作用:
suspend operator fun invoke(reference: Reference): Date {
val date = reference.tagId
?.let { tagRepository.getTag(it) }
?.uploadDate ?: Date()
.apply { time += accountRepository.getAccount().first().defaultExpiryPeriod }
return date.roundToMidnight()
}
roundToMidnight() 返回Date 的新实例
fun Date.roundToMidnight(): Date {
val calendar = Calendar.getInstance()
calendar.time = this
calendar[Calendar.HOUR_OF_DAY] = 23
calendar[Calendar.MINUTE] = 59
calendar[Calendar.SECOND] = 59
calendar[Calendar.MILLISECOND] = 0
return Date(calendar.timeInMillis)
}
是什么导致了这两种功能的差异?我会说它们会完全一样,我看到自己在一个月内将无错误功能重构为原始功能,因为我忘记了这种情况。
【问题讨论】:
-
apply和roundToMidnight在Date()上被调用,并且只有在?:之前的表达式返回 null -
谢谢!是否可以内联,以便在
uploadDate ?: Date()而不是Date()上调用apply和roundToMidnight? -
使用括号
(reference?. ... ?.uploadDate ?: Date()).apply { ... }.roundToMidnight() -
我强烈建议在不使用
let或apply的情况下重写此sn-p 代码。正如您自己所看到的,这些函数使您的代码更难阅读和推理,并引入了一个微妙的错误。代码简洁并不总是一件好事。
标签: android kotlin extension-function