首页 > 解决方案 > 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
    }
}

实际上,目标永远不会改变,即使价值达到了目标。

标签: kotlin

解决方案


对我来说,你的代码工作正常。(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 的调用,否则你的第一个“当前”目标将来自索引 1,因此跳过索引 0。)


推荐阅读