分配不是表达式,在这种情况下只能使用表达式-Kotlin

时间:2018-07-23 11:04:52

标签: android android-studio kotlin

将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)显示错误显示

  

赋值不是表达式,并且只允许使用表达式   这种情况

2 个答案:

答案 0 :(得分:1)

您不能做这样的事情:

diffInSeconds = diffInSeconds / 60

,如果它不被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]
}

答案 1 :(得分:1)

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

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