1

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

michid
  • 10,536
  • 3
  • 32
  • 59
gervais.b
  • 2,294
  • 2
  • 22
  • 46
  • 3
    Maybe you can try Scala 3 http://dotty.epfl.ch/docs/reference/new-types/union-types.html – Emiliano Martinez Dec 24 '20 at 10:23
  • Does this answer your question? [Scala variable with multiple types](https://stackoverflow.com/questions/43495047/scala-variable-with-multiple-types) – Tomer Shetah Dec 24 '20 at 10:45
  • @TomerShetah no, not really. That answer is the same as my proposal with _sealed trait_. My question was to have a simpler way to declare them. – gervais.b Dec 24 '20 at 10:58
  • 2
    Scala 2 doesn't natively support coproduct. Use shapeless library or wait for Scala 3 – SwiftMango Dec 24 '20 at 12:29
  • 1
    Can you explain what you mean by "OR composition"? From my admittedly limited knowledge of F#, what you show has nothing to do with "OR" or "composition", but is simply a Closed Algebraic Sum Type. – Jörg W Mittag Dec 24 '20 at 14:32
  • It would *really* help if you could define precisely what you are looking for. So far, one answerer has interpreted your question as being about *sum types* while another answerer has interpreted your question as being about *union types* which are two very different things. It is totally unclear what you mean by "OR composition". I could not find that term in the F# Language Specification or any documentation associated with F#, nor in the Scala Language Specification or documentation, and Google doesn't seem to know it either. – Jörg W Mittag Dec 26 '20 at 14:06

2 Answers2

2

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)

https://dotty.epfl.ch/docs/reference/enums/adts.html

Matthias Berndt
  • 4,387
  • 1
  • 11
  • 25
0

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.

michid
  • 10,536
  • 3
  • 32
  • 59