Joint Case Clauses in Switch Statements
See original GitHub issueI assume that you left out case
fallthrough in the switch
statement by design. Indeed, fallthrough can be tricky for newcomers to the language. On the other hand, switch
feels slightly crippled without it.
Here is an example of the current behaviour:
switch command
case "-lvlup" // Currently doesn't do anything. I'm used to fallthrough so this came as a surpise for me.
case "-lu"
lvlup()
I’d like to execute the same statement for both case
clauses without repeating the statement. This is currently not possible.
I propose the following solution: Joint case
clauses. E.g.,
switch command
case "-lvlup", "-lu"
lvlup()
It’s an alternative approach to fallthrough without the ambiguity. I’ve used the a comma symbol to separate the literals in the case
clause. If you prefer another symbol then just use your preference.
Assuming that switch
compiles to a long if..elseif..else
statement, the implementation can simply or
together the arguments of the joint case
clause.
What do you think? Is it worth the effort?
Issue Analytics
- State:
- Created 5 years ago
- Comments:7 (4 by maintainers)
Top GitHub Comments
Several cases can now be combined using a pipe symbol (
|
).I used the pipe rather than a comma, because a comma is often used for things like tuples and function parameters and we might add language features to match on tuples in the future.
Yes, switch was implemented in the most basic manner with the only additional thing being that it checks if all cases of an enum are handled. I think improvements could be made, perhaps even syntax wise similar to Kotlin’s when.