Discussion Question: Why doesn't dart allow to declare enums in class?

Viewed 544

I tried to declare an enum inside the class and it gave me an error stating can't have enum inside a class. I wanted to know the reason why but I didn't find anything on the internet. Declaring enum inside a class is allowed by major languages why not dart?

2 Answers

Dart does not allow nested type declarations in general. You can only declare types at top-level. This includes classes, mixins, typedefs and enums.

I believe the original reason was that it was not necessary, and implementing it inadequately was worse than not doing allowing it at all.

There is nothing inherently preventing Dart from allowing static types declared inside other types. Obviously, if Dart allowed classes statically declared inside classes, it would allow in arbitrary nesting of classes, so it really is a matter of allowing zero, one or an infinite amount of nesting. Dart currently has "one'. Still, it's something that can be easily remedied if deemed wort the effort and a higher priority than other language changes.

The other option is to have non static nested types. That's a much bigger can of worms, and probably not something that's going to happen any time soon, if ever.

Dart doesn't allow declaring of Enum inside the class as far as I know. I've made that error before and it took me a minute to figure out what was wrong with my code. Declare/setup your Enum before your class like so:

enum Gender {
     male,
     female,
}

/// Then declare your class next
class MyClass {
/// The rest of your code goes here, and you still have access to your enum
}
Related