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
Stephan Schröder
11/19/2022, 3:16 PM
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).
Stephan Schröder
11/19/2022, 3:17 PM
(--triesLeft)
might not work though. If I'm not mistaken, then parameters are immutable. (so use
(triesLeft-1)
instead )
g
Georg Ekeberg
11/19/2022, 3:19 PM
Ok! Thanks, great answers.
s
Stephan Schröder
11/19/2022, 3:27 PM
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
Georg Ekeberg
11/19/2022, 3:32 PM
Yeah, JS/TS, and a bit of clojure
s
Stephan Schröder
11/19/2022, 3:34 PM
have fun discovering how static types can benefit you (even stricter than in TS). basically you gain security, but mocking gets harder.