Kotlin类的属性不变

时间:2019-08-30 06:08:43

标签: kotlin

我想开设一个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
    }
}

实际上,即使值达到目标,目标也不会改变。

1 个答案:

答案 0 :(得分:0)

对我来说,您的代码可以正常工作。 (Java 11 AdoptOpenJDK上的Kotlin 1.3.50)

像这样运行它:

class TargetApp {}
fun main() {
    val targets = Targets(arrayListOf(Target("one"), Target("two"), Target("three")))

    var numberRepetitions = 0;
    for(i in 1..10){
        val current = targets.currentTarget()
        val repetitionMade = targets.updateTarget()
        if(repetitionMade){
            numberRepetitions += 1
        }
        println("Index $i with current target '${current.name}' and $numberRepetitions repetitions")
    }
}

带有目标

data class Target(
    val name: String
)

和“目标”

class Targets(private val targets: ArrayList<Target>) {
    init {
        require(targets.size > 1) { "There must be more than one target in targets" }
    }

    private var x = 0

    fun currentTarget(): Target {
        return targets[x]
    }

    fun updateTarget(): Boolean {
        x += 1
        x %= targets.size
        return x == 0
    }
}

输出:

Index 1 with current target 'one' and 0 repetitions
Index 2 with current target 'two' and 0 repetitions
Index 3 with current target 'three' and 1 repetitions
Index 4 with current target 'one' and 1 repetitions
Index 5 with current target 'two' and 1 repetitions
Index 6 with current target 'three' and 2 repetitions
Index 7 with current target 'one' and 2 repetitions
Index 8 with current target 'two' and 2 repetitions
Index 9 with current target 'three' and 3 repetitions
Index 10 with current target 'one' and 3 repetitions

我想你的问题出在其他地方。

(我交换了currentTarget和updateTarget的调用,因为否则,您的第一个“当前” Target将来自索引1,因此跳过索引0。)