Currently, creating an object variant type like this:
    
    
    type
      FooKind = enum a, b, c
      Foo = object
        case kind: FooKind
        of a:
          bar, a: int
        of b:
          bar, b: int
        of c:
          c: int
    
    
    Run

results in an error:

> Error: attempt to redefine: 'bar'

because the different branches of the variant cannot share fields. There's an 
[open issue about that](https://github.com/nim-lang/RFCs/issues/19) but since 
it's over 3 years old and still unresolved, I'm not holding my breath.

I see a few possible alternatives:

  * Making the "shared" fields common to all variants, which would pollute some 
variants with unnecessary fields:


    
    
    type
      FooKind = enum a, b, c
      Foo = object
        bar: int
        case kind: FooKind
        of a:
          a: int
        of b:
          b: int
        of c:
          c: int
    
    
    Run

  * Using a static enum, which seems to necessitate [additional 
workarounds](https://forum.nim-lang.org/t/3150):


    
    
    type
      FooKind = enum a, b, c
      Foo[K: static[FooKind]] = object
        when K == a:
          bar, a: int
        elif K == b:
          bar, b: int
        elif K == c:
          c: int
    
    
    Run

  * Using regular object inheritance:


    
    
    
    type
      FooKind = enum a, b, c
      FooBase = object
        kind: FooKind
      FooA = object of FooBase
        bar, a: int
      FooB = object of FooBase
        bar, b: int
      FooC = object of FooBase
        c: int
    
    
    Run

Are there other alternatives to getting around this issue? 

Reply via email to