Is that possible to add literal types (like what t...
# language-evolution
m
Is that possible to add literal types (like what typescript has) to Kotlin? and add a limited version of union type (like what is introduced for Rich Error feature) for literal types? So make some really fun and helpful things possible:
Copy code
fun rollDice(): 1 | 2 | 3 | 4 | 5 | 6 {...}
or
Copy code
fun switch(switch : "on" | "off") { ... }
👀 1
🙌 1
j
Value classes already give you a type safe reduction of values. Not sure we need this, too.
m
Yes, I agree, value classes work for performance, but to me literal types would be much simpler and need far less boilerplate. (I believe they are also type safe and we can define them with
typealias
to make them reusable and readable)
m
This is out of scope for unions. In fact, in my opinion, it's closer to something like "const parameters" and the whole topic of comp-time evaluation, since here it's less about types (types from the example doesn't make much sense) and more about the values you can pass and what the compiler can track
m
that's true, but the way that I see this as union type is that here each number is treated as a type itself. Each constant value is itself a type:
Copy code
val a : 5 = 5
or
Copy code
val b : "on" = "on"
So we can combines literal types like
1 | 2
or
"on" | "off"
I know that it is possible with enums, sealed class and value classes with private constructor but creating those just for a private function feels like overkill. 😅
☝️ 1