That question may be a dumb one where any search engine should give me a quick answer. However I did not find anything, so I may use the wrong terms.
If F# one can do an exclusive (OR) composition with the |
symbol:
type LeftOrRightOrNone =
| Left of string
| Right of string
| None
Which mean that a LeftOrRightOrNone
can only be of type Left
OR Right
OR None
.
We can have the same constraint with a sealed trait :
sealed trait LeftOrRightOrNone
case class Left(..) extends LeftOrRightOrNone
case class Right(..) extends LeftOrRightOrNone
case object None extends LeftOrRightOrNone
But I wonder if there is a simpler way to declare such types in Scala?
Thanks
In Scala 2 you need to write it with sealed traits and case classes like you described. Scala 3 has much nicer syntax for this:
enum Either[+A, +B]:
case Left(a: A)
case Right (b: B)
There is no such thing in Scala. You have to approximate it via sealed traits as shown.
However, there is a way to encode union types leveraging the Curry-Howard Isomorphism.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.