elect
02/02/2023, 9:10 AMRange
on enums?Sam
02/02/2023, 9:14 AMelect
02/02/2023, 9:15 AMSam
02/02/2023, 9:16 AMelect
02/02/2023, 9:18 AMisGamepad
can become this in Gamepad_BEGIN until Gamepad_END
elect
02/02/2023, 9:19 AMCLOVIS
02/02/2023, 9:21 AMenum class Test {
A,
B,
C,
;
}
println(Test.A.ordinal in Test.B.ordinal until Test.C.ordinal)
?elect
02/02/2023, 9:21 AM.ordinal
Sam
02/02/2023, 9:22 AM..
, not with until
.Sam
02/02/2023, 9:24 AMuntil
only works for integral types, because a until b
is basically implemented as a..(b - 1)
. It doesn’t work for enum types because they don’t have addition and subtraction 😄.elect
02/02/2023, 9:24 AMSam
02/02/2023, 9:25 AMCLOVIS
02/02/2023, 9:25 AMenum class Test {
A,
B,
C,
;
}
infix fun Test.until(end: Test) = this..(enumValues<Test>()[end.ordinal-1])
println(Test.B in Test.A..Test.B)
println(Test.B in Test.A until Test.B)
CLOVIS
02/02/2023, 9:26 AMend
is the first element of the enum, but you get the ideaSam
02/02/2023, 9:26 AMval Gamepad_BEGIN = GamepadStart
val Gamepad_END = GamepadRStickDown
val isGamepad: Boolean
get() = this in Gamepad_BEGIN..Gamepad_END
Sam
02/02/2023, 9:26 AMGamepad_END
boundary is inclusive rather than exclusive)elect
02/02/2023, 9:27 AMAdam S
02/02/2023, 9:31 AMsealed interface Key {
enum class Keyboard : Key { A, B, C, ... }
enum class Gamepad: Key { Start, Back, Left, ... }
}
Then you can check using is
fun checkKey(key: Key) {
when (key) {
is Gamepad -> {}
is Key -> {}
}
}
Or, if you want to keep the keys ‘flat’ and not nested, and if you want the keys to have multiple ‘types’, use objects instead of enums.
sealed interface Key {
sealed interface Keyboard: Key
sealed interface Gamepad: Key
sealed interface DirectionKey: Key
object A: Keyboard, DirectionKey
object B: Keyboard
object C: Keyboard
//...
object W: Keyboard, DirectionKey
object S: Keyboard, DirectionKey
object D: Keyboard, DirectionKey
object GamepadLeft: Gamepad, DirectionKey
object GamepadRight: Gamepad, DirectionKey
}
Just throwing out ideas - it might be overkill and too complicated!elect
02/02/2023, 9:31 AM