【问题标题】:Assignments are not expressions and only expressions are allowed in this context - Kotlin赋值不是表达式,在这种情况下只允许使用表达式 - Kotlin
【发布时间】:2018-07-23 11:04:52
【问题描述】:

我在将 java 转换为 kotlin 时遇到错误,无法理解如何解决此特定错误。

internal fun getDiff(to: Calendar, from: Calendar): Long {

        var diffInSeconds = (to.time.time - from.time.time) / 1000

        val diff = longArrayOf(0, 0, 0, 0)
        diff[3] = if (diffInSeconds >= 60) diffInSeconds % 60 
                    else diffInSeconds // sec
        diff[2] = if ((diffInSeconds = diffInSeconds / 60)>= 60)
                         diffInSeconds % 60
                 else
                        diffInSeconds // min
        diff[1] = if ((diffInSeconds = diffInSeconds / 60) >= 24)
                        diffInSeconds % 24
                 else
                        diffInSeconds // hour
        diff[0] = (diffInSeconds = diffInSeconds / 24) // day

        Log.e("days", diff[0].toString() + "")

        return diff[0]
}

下一行:(diffInSeconds = diffInSeconds / 60) 显示错误显示

赋值不是表达式,只能使用表达式 这个上下文

【问题讨论】:

  • 看看this
  • 错误是不言自明的,您在编译器期望表达式的地方进行赋值。

标签: android android-studio kotlin


【解决方案1】:

你不能这样做:

diffInSeconds = diffInSeconds / 60

在 if 中,kotlin 不支持。 你必须在 if 之前或之后提取它。

例如

internal fun getDiff(to: Calendar, from: Calendar): Long {

    var diffInSeconds = (to.time.time - from.time.time) / 1000

    val diff = longArrayOf(0, 0, 0, 0)
    diff[3] = if (diffInSeconds >= 60) diffInSeconds % 60
    else diffInSeconds // sec
    diffInSeconds /= 60
    diff[2] = if (diffInSeconds >= 60)
        diffInSeconds % 60
    else
        diffInSeconds // min
    diffInSeconds /= 60
    diff[1] = if (diffInSeconds >= 24)
        diffInSeconds % 24
    else
        diffInSeconds // hour
    diffInSeconds /= 24
    diff[0] = (diffInSeconds) // day


    return diff[0]
}

【讨论】:

  • 如果我将表达式存储在另一个变量中并每次都检查呢?
  • 这取决于你想用它做什么。您可以再创建一个 var 并在其中存储您的 if 参数而不更改您的主要值。
【解决方案2】:

语法无效,因为diffInSeconds = diffInSeconds / 60 不是 Kotlin 中的表达式。就这样做

var a = diffInSeconds /= 60
diff[1] = if (a >= 24)

【讨论】:

  • 每次迭代都必须遵循这种方式。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-24
  • 1970-01-01
  • 1970-01-01
  • 2021-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多