Search code examples
scalaenumsgadtdottyscala-3

Invariant default type for enums in Scala 3


Scala 3 now has an improved way to define ADTs. A syntactic sugar that removes all the hassle of doing them with the usual sealed trait way.

So I'll explain my question with an example

enum Adt[+A]{
    case Option1
    case Option2
}

In this case Option1 and Option2 are of type Adt[Nothing], because the type parameter A is covariant.

If the enum were contravariant, they would be of type Adt[Any].

But what if it is invariant?


Solution

  • In Dotty 0.27.0-RC1, this is an error:

    
    scala> enum Adt[A]{
         |     case Option1
         |     case Option2
         | }
    2 |    case Option1
      |    ^^^^^^^^^^^^
      |    cannot determine type argument for enum parent class Adt,
      |    type parameter type A is non variant
    3 |    case Option2
      |    ^^^^^^^^^^^^
      |    cannot determine type argument for enum parent class Adt,
      |    type parameter type A is non variant