【问题标题】:Last extension function is not called最后一个扩展函数没有被调用
【发布时间】: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)
}

是什么导致了这两种功能的差异?我会说它们会完全一样,我看到自己在一个月内将无错误功能重构为原始功能,因为我忘记了这种情况。

【问题讨论】:

  • applyroundToMidnightDate() 上被调用,并且只有在 ?: 之前的表达式返回 null
  • 谢谢!是否可以内联,以便在 uploadDate ?: Date() 而不是 Date() 上调用 applyroundToMidnight
  • 使用括号(reference?. ... ?.uploadDate ?: Date()).apply { ... }.roundToMidnight()
  • 我强烈建议在不使用letapply 的情况下重写此sn-p 代码。正如您自己所看到的,这些函数使您的代码更难阅读和推理,并引入了一个微妙的错误。代码简洁并不总是一件好事。

标签: android kotlin extension-function


【解决方案1】:

正如 Egor 所建议的,表达式体并不总是最好的解决方案。改写成这样。

suspend operator fun invoke(reference: Reference): Date {
    val tag = reference.tagId?.let { tagRepository.getTag(it)}
    val uploadDateOrNow = tag?.uploadDate ?: Date()

    uploadDateOrNow.time += defaultExpiryPeriod()
    return uploadDateOrNow.roundToMidnight()
}

private suspend fun defaultExpiryPeriod() = accountRepository
    .getAccount().first()
    .defaultExpiryPeriod

在做我自己的项目,男孩,我是否想念在 PRs 中被批评的一段时间。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-10
    • 2018-07-05
    • 2019-08-05
    • 1970-01-01
    • 1970-01-01
    • 2014-08-08
    • 1970-01-01
    相关资源
    最近更新 更多