Is this climbing uphill with Kotlin? Should I just...
# getting-started
g
Is this climbing uphill with Kotlin? Should I just create my own datastructure GameState with getters, constructors and setters? Or is there a good way to do this with the inbuilt map structure?
s
mapOf
returns a Map-Implementation which doesn't extend from
GameState
. Your
GameState
isn't even Map-like, it's Pair-like. but if all you're looking for is correct typing, why not simply have
Copy code
fun roll(pinsDown: Int,
         pinsLeft: Int = 10,
         triesLeft: Int = 2): Map<Int,Int> {
    return mapOf( (pinsLeft - pinsDown) to (--triesLeft))
}
to
is an generic infix function that returns -in this case- a
Pair<Int, Int>
(because what you're providing is two Ints).
(--triesLeft)
might not work though. If I'm not mistaken, then parameters are immutable. (so use
(triesLeft-1)
instead )
g
Ok! Thanks, great answers.
s
of course you can also return a
GameState
but then use the GameState-constructor, not a Map-generating function:
Copy code
fun roll(pinsDown: Int,
         pinsLeft: Int = 10,
         triesLeft: Int = 2): GameState {
    return GameState(
        pinsLeft = pinsLeft - pinsDown,
        triesLeft = triesLeft-1,
    )
}
that's probably what you want to do. Your approach of creating objects by crating Maps was a step in the wrong direction (do you come from JavaScript? Your approach looks like trying to do dynamic typing in a language that has static typing to me).
g
Yeah, JS/TS, and a bit of clojure
s
have fun discovering how static types can benefit you (even stricter than in TS). basically you gain security, but mocking gets harder.
🙌 1