language icon indicating copy to clipboard operation
language copied to clipboard

Allow .index of enums inside switch statements.

Open erenpal opened this issue 3 weeks ago • 1 comments

According to the https://dart.dev/language/enums

Each value in an enum has an index getter, which returns the zero-based position of the value in the enum declaration. For example, the first value has index 0, and the second value has index 1.

Position of a value in enum is known at compile time because enums are constant. But compiler and analyzer complains inside switch statement,

The property 'index' can't be accessed on the type 'myEnum' in a constant expression.

This shouldn't happen. There is a similar issues closed https://github.com/dart-lang/language/issues/312. https://github.com/dart-lang/sdk/issues/29278

erenpal avatar Dec 07 '25 13:12 erenpal

It's not impossible to allow. It is indeed always available at compile-time, and there is no way it can possibly not be. You're not allowed to override or hide the index getter.

That said, it's not that useful. It has a one-to-one correspondence with enum values, and you should almost always use the enum value instead of its index. The only case where that may not be possible is when you're parsing a serialized form, which stores the indices, into an enum value. At that point, you shouldn't be using a constant pattern to switch over the indices, you should just do EnumName.values[theIndex] first, and then maybe switch on that.

Do you have any other concrete use-case in mind?

lrhn avatar Dec 09 '25 14:12 lrhn