I want to model the result of two six sided dice in Kotlin. In TypeScript you can do something like this:
type SixSidedDie = 1 | 2 | 3 | 4 | 5 | 6
I would like to do something similar in Kotlin with
typealias SixSidedDie = 1 | 2 | 3 | 4 | 5 | 6
Which of course doesn't work because the compiler expects a type. Is there any way in Kotlin to use constant values as a type?
Is there any way in Kotlin to use constant values as a type?
Not at the moment, and I haven't seen it discussed so far. This is because, without union types, I don't think those are really useful (you could use objects for that purpose).
There is an issue tracking the possible addition of denotable union types to the language: https://youtrack.jetbrains.com/issue/KT-13108/Denotable-union-and-intersection-types
Now about your precise use case, there is also nothing currently available in Kotlin to represent subsets of numbers as a type. The closest you can get, as mentioned in the comment, is an enum:
enum class Dice6Result {
ONE, TWO, THREE, FOUR, FIVE, SIX
}
Or with an associated Int value if you need it:
enum class Dice6Result(val value: Int) {
ONE(1), TWO(2), THREE(3), FOUR(4), FIVE(5), SIX(6)
}
Note, that union types still would not solve the Int subset problem unless constant values could be used as types (as you were asking for).
Another option for you could be to use a value class to wrap the integer value, and check in an init block at construction time that the value is within the bounds. However, this becomes a runtime check, which might be less interesting than an enum.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With