Pre-SIP: Tagged enum's variant inference

Scala doesn’t allow the following:

enum E:
  case VAR_A
  case VAR_B

val e: E = VAR_A

This is only allowed if you import E._.

My proposal is roughly:

enum E:
  case VAR_A
  case VAR_B

val e: E = "var_a"

What happens:

  • A string literal with an enum context may resolve to a variant by matching it with its lowercase snake-form. If the variant’s class name is not in SCREAMING_SNAKE_CASE, convert it to lowercase snake-form at best effort.

Conversion from/into String

For tagged enums, allow fallible conversion conversion from any String.

For tagged enums, allow successible conversion into String.

Enums tagged with number

Ditto, with a valueOf method.

Thank you for writing this up. However, I’m afraid this is not the Scala way. We don’t use strings for enum values. If import E._ bothers you, you can do export E._ once in the same file as enum E:, and then you get the members everywhere.

5 Likes

Yep, but I believe this can cause conflicts. Say you’ve multiple UI design components… one has PRIMARY, SEFONDARY… and another one has a few more.

Then you don’t do that and you write E.PRIMARY.

Although there is somewhere a more extensive proposal/discussion that would let you write PRIMARY where an E is expected.

Btw: using all caps is not a common style in Scala. We prefer PascalCase for enum values, like for objects and classes.

3 Likes