Is this a viable approach? ```data class GameState...
# getting-started
g
Is this a viable approach?
Copy code
data 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
        }
    }
}
j
Using a
Map
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:
Copy code
data class GameState(
    private val pinsLeft: Int,
    private val triesLeft: Int,
)
Then you can access the properties of a state by using the
.
syntax:
Copy code
val state = GameState(pinsLeft = 42, triesLeft = 5)

roll(state.pinsLeft, state.triesLeft)
g
Aha good, that's simple and what I am after! Used to dynamic functional programming, but when I know the keys, defining them is definately a good idea.
j
There is also the benefit that the values can have different types, and that you can guarantee that the values are present because the types are non-nullable. So basically the constructor cannot be called with null values
You also benefit from the compiler checks for the names of the properties (making a typo in the key wouldn't compile here, while with a map the compiler cannot check your string keys)
s
indeed, static type-checking for the win 😎