在Kotlin中满足条件时,最干净的方法来重新分配变量的值
比方说,我有一些方法递减的Long变量。 我想将其设置为60后减到0.我尝试应用函数
private var tempTime = interval.apply { if (this.equals(0L)) tempTime = interval }
但它甚至不是正确的语法。
tempTime
是我的变量,它会减少, interval
是我想在tempTime
达到0之后设置的默认值。另外,有没有什么办法可以避免这个丑陋的, if equals 0L
语句?
在Kotlin中, if
statement 是一个表达式,那么你可以这样写:
var tempTime: Long = 60 ... val interval = 60L tempTime = if (tempTime == 0L) { interval } else { tempTime - 1 }
你when
可以使用。 在我看来,它看起来更干净。
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
使用Backing Field
var tempTime = 0 set(newValue) { if ( newValue < - 50 ) { field = 0 } else { field = newValue } }
使用Backing Properties
private var _tempTime = 0 var tempTime: Int get() { return _tempTime } set(newValue) { if ( newValue < - 50 ) { _tempTime = 0 } else { _tempTime = 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 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 } } }