oday
11/19/2020, 9:06 AMprivate fun resetCounterAndGame(counter: Int) {
if (counter == 2) {
gameButtonText.set(resProvider.getString(R.string.try_another_number))
gameStarted = false
counter = 0 <--- val cannot be reassigned of course
}
}
wbertan
11/19/2020, 9:08 AMcounter
?oday
11/19/2020, 9:08 AMthingImTryingToCount = resetGameAndCounter(thingImTryingToCount)
counter.reset()
and if this == 2 return 0 else return this
wbertan
11/19/2020, 9:15 AMMutableStateFlow
instead? So you can pass the reference and set a new value, and whenever reads the state flow would always pick the latest value.oday
11/19/2020, 9:16 AMVampire
11/19/2020, 9:39 AMval
cannot be reassigned, but that you confuse pass-by-value and pass-by-reference.Int
you just pass the 2
private fun resetCounterAndGame(counter: KMutableProperty<Int>) {
if (counter.getter.call() == 2) {
gameButtonText.set(resProvider.getString(R.string.try_another_number))
gameStarted = false
counter.setter.call(0)
}
}
and then pass the reference to the field with resetCounterAndGame(::counter)
or similar, but I would strongly advice to not do this.Tobias Berger
11/19/2020, 9:47 AMVampire
11/19/2020, 9:56 AMprivate fun resetCounterAndGame(counter: Int, counterSetter: (Int) -> Unit) {
if (counter == 2) {
counterSetter(0)
}
}
fun main() {
var counter = 1
println(counter)
resetCounterAndGame(counter++) { counter = it }
println(counter)
resetCounterAndGame(counter++) { counter = it }
println(counter)
}
=>
1
2
0
Kirill Grouchnikov
11/19/2020, 2:15 PMRyan
11/19/2020, 2:47 PM