在Kotlin中满足条件时重新分配变量值的最干净方法

在Kotlin中满足条件时重新分配变量值的最干净方法,kotlin,Kotlin,假设我有一个长变量,它通过某种方法递减。 我想在其减为0后将其设置为60。我试着应用这个函数 private var tempTime = interval.apply { if (this.equals(0L)) tempTime = interval } 但它的语法甚至都不正确 testime是我要递减的变量,interval是我要在testime达到0后设置的默认值。还有,有没有办法避免这种丑陋的if=0L语句?在Kotlinif语句中,因此您可以编写: var temp

假设我有一个长变量,它通过某种方法递减。 我想在其减为0后将其设置为60。我试着应用这个函数

  private var tempTime = interval.apply {
    if (this.equals(0L)) tempTime = interval
  }
但它的语法甚至都不正确


testime
是我要递减的变量,
interval
是我要在
testime
达到0后设置的默认值。还有,有没有办法避免这种丑陋的
if=0L
语句?

在Kotlin
if
语句中,因此您可以编写:

var tempTime: Long = 60
...
val interval = 60L
tempTime = if (tempTime == 0L) {
    interval
} else {
    tempTime - 1
}

使用
支持字段

var tempTime = 0
    set(newValue) {
        if ( newValue < - 50 ) {
            field = 0
        } else {
            field = newValue
        }
    }

如果要将其封装到可重用类中:

class RepeatingInterval(val interval: Int, var current: Int = 0) {
    fun dec(): Int {
        current = if (current == 0) interval else current-1
        return current
    }
}
然后你可以:

val counter = RepeatingInterval(60)

// whenever you want to decrement it without worrying about it rolling over
val tempTime = counter.dec()
您还可以添加一个
inc()
方法,以使间隔变为另一种方式:

class RepeatingInterval(val interval: Int, var current: Int = 0) {
    fun dec(): Int {
        current = if (current <= 0) interval else current-1
        return current
    }

    fun inc(): Int {
        current = if (current >= interval) 0 else current+1
        return current
    }
}
class RepeatingInterval(val间隔:Int,var当前:Int=0){
fun dec():Int{
当前=如果(当前=间隔)0其他当前+1
回流
}
}
以上都不是线程安全的。如果您想要线程安全:

class RepeatingInterval(val interval: Int, starting: Int = 0) {
    val current = AtomicInteger(starting)

    fun dec(): Int {
        return current.accumulateAndGet(-1) { prev, x -> if (prev <= 0) interval else prev + x }
    }

    fun inc(): Int {
        return  current.accumulateAndGet(+1) { prev, x -> if (prev >= interval) 0 else prev + x }
    }
}
class RepeatingInterval(val interval:Int,start:Int=0){
val current=AtomicInteger(开始)
fun dec():Int{
返回当前.acgregateAndGet(-1){prev,x->if(prev-if(prev>=interval)0 else-prev+x}
}
}

你可以在时使用
。在我看来,它看起来更干净

var tempTime = 0L
val interval = 5L
tempTime = when (tempTime) {
    0L -> interval
    else -> tempTime
}

我不认为这是特定于语言的。如果您想隐藏这种行为,请使用@jasonminard的答案。如果您的目标是在代码中表达它,请使用C、Java或任何其他语言:

var tempTime = 60L
val mod = (60 + 1)

// decrement:
tempTime = (tempTime - 1 + mod) % mod
var tempTime = 60L
val mod = (60 + 1)

// decrement:
tempTime = (tempTime - 1 + mod) % mod