Reputation: 15113
I saw that in F# its very easy to define a type which is a combined from a set of other types such as
type MyFiveNumbers = One | Two | Three | Four | Five
This looks just great!
What is the simplest way to do that in Scala?
Upvotes: 1
Views: 136
Reputation: 170805
One
and the rest are not types, but union cases. The Scala equivalent in fact does make them types:
sealed trait MyFiveNumbers
case object One extends MyFiveNumbers
case object Two extends MyFiveNumbers
...
In such a simple case you might be best off just using a Java enum. However, if any constructors have parameters (e.g. add | Other of int
to the end), they correspond to Scala case classes:
case class Other(x: Int) extends MyFiveNumbers
You can use pattern matching just as in F#:
// x has type MyFiveNumbers
x match {
case One => ...
...
case Other(n) => ...
}
and get compiler warnings about incomplete matches (only if the sealed
keyword is used; otherwise you can create additional cases in other files).
Upvotes: 5