【发布时间】:2019-08-30 15:04:52
【问题描述】:
我想要一个 kotlin 类来管理一些练习的当前目标。为此有两个主要函数,updateTarget(),它转到列表中的下一个目标,currentTarget(),它只是返回当前目标。
但是,目标从未真正改变过。 x 始终为 0。
我对此有两个问题。首先,为什么属性没有变化?其次,我是否缺少另一种更适合我的目标的设计模式?
class Targets(private val targets: ArrayList<Target>)
{
init {
require(targets.size > 1) {"There must be more than one target in targets"}
}
// Keeps track of current index of target. Has a range of 0 to targets.size-1
private var x = 0
/**
* Returns the current exercise target
*/
fun currentTarget() : Target {
return targets[x]
}
/**
* Updates the current exercise target to the next target in the list
*
* Returns true if a repetition has been made.
*/
fun updateTarget() : Boolean {
x += 1
x %= targets.size
return x == 0
}
}
代码调用者:
if (target.isMetBy(value)) {
val repetitionMade = currentExercise.targets.updateTarget()
target = currentExercise.targets.currentTarget()
if (repetitionMade) {
numberRepetitions += 1
}
}
实际上,目标永远不会改变,即使价值达到了目标。
【问题讨论】:
标签: kotlin