Georg Ekeberg
11/19/2022, 3:04 PMdata class GameState(val i: Int, val i1: Int) {
private val pinsLeft = i
private val triesLeft = i1
operator fun get(s: String): Int {
when (s) {
"pinsLeft" -> return pinsLeft
"triesLeft" -> return triesLeft
}
}
}
Joffrey
11/19/2022, 3:08 PMMap
is possible, but not very convenient. Maps should be used when the keys are dynamic. Here you know what the properties of your state are, so you don't want to access the properties of your state as strings. You should use a class with properties instead.
This is how you write your own class with 2 properties, a constructor that takes in the values of those properties, and proper `equals`/`hashCode`/`toString` methods:
data class GameState(
private val pinsLeft: Int,
private val triesLeft: Int,
)
Then you can access the properties of a state by using the .
syntax:
val state = GameState(pinsLeft = 42, triesLeft = 5)
roll(state.pinsLeft, state.triesLeft)
Georg Ekeberg
11/19/2022, 3:21 PMJoffrey
11/19/2022, 3:27 PMJoffrey
11/19/2022, 3:29 PMStephan Schröder
11/19/2022, 3:30 PM