Suppose I've got enumeration A :
object A extends Enumeration { type A = Int; val A1 = 1; val A2 = 2; val A3 = 3 }
Also, I have a function defined only for A1 or A2 but not for A3.
def foo(a: A): Int = a match {
case A.A1 => 1 // do something
case A.A2 => 2 // do something else
case A.A3 => throw new UnsupportedOperationException()
}
Now I would like to get a compilation error for foo(A.A3).
In pseudocode I define foo like this:
def foo(a: A1 | A2): Int = ???
How would you suggest write foo to prevent calling it with A.A3 ?
The given pseudo code is on the right track; the supported types need to be in the type signature of
fooand unsupported types not.Compilation error:
To make this possible in scala 2 (literal types needed, so only scala 2.13 or Typelevel's 2.12) we need give a more refined type to the
A1-A3constants, and an implicit conversion to the 'union' typeA12:Compilation fails with:
AnA12is private to make it impossible to usefoo(AnA12(A3)).