0

I'm using case objects to define an enumeration thusly:

sealed trait Fruit
case object Apple extends Fruit
case object Orange extends Fruit
case object Banana extends Fruit

This is in-line with this official example for case objects.

Is it possible to define a type that is either an Apple or an Orange, but never a Banana?

val appleOrOrange: Either[Apple, Orange]

This ^ doesn't work, because Apple and Orange themselves are not types, but singleton case objects. Is it possible to constrain this type to only accept one or the other?

Cory Klein
  • 51,188
  • 43
  • 183
  • 243

1 Answers1

1

When referring to the types of Apple and Orange you can use type to access the singleton type:

val appleOrOrange: Either[Apple.type, Orange.type]
Cory Klein
  • 51,188
  • 43
  • 183
  • 243