Crell / enum-comparison

A comparison of enumerations and similar features in different languages
82 stars 7 forks source link

Attributes on enums #22

Closed bwoebi closed 3 years ago

bwoebi commented 4 years ago

Quoting example from rightfold: https://chat.stackoverflow.com/transcript/message/50502258#50502258

enum Suit {
    use EnumString, EnumInt; // these traits use the AsString and AsInt attributes
    #[AsString('H'), AsInt(1)] case Hearts;
    #[AsString('C'), AsInt(2)] case Clubs;
    #[AsString('D'), AsInt(3)] case Diamonds;
    #[AsString('S'), AsInt(4)] case Spades;
}

I think that's a good usage of attributes - and having a good usage available, we should probably allow them.

bwoebi commented 4 years ago

We may even consider a couple native traits/primitives as part of the standard library (because it feels to me like this could be a common pattern, but if we don't do that ourselves, every library will just roll their own over and over again).

iluuu1994 commented 4 years ago

Sounds sensible. Adding an attribute there would probably just add it to the underlying case class.

Crell commented 3 years ago

The RFC as written uses a Swift-like syntax for primitives. I'm not sure that there's a good reason to do both that and attributes.

iluuu1994 commented 3 years ago

I think just propagating the attributes to the case class would make most sense.

#[FooAttribute]
enum Foo {
    #[BarAttribute]
    case Bar;
}

// -->

#[FooAttribute]
sealed class Foo {}

#[BarAttribute]
class Bar extends Foo {}