The main enumerations in Scala awkward:
- If you want to use them against a pattern, you will not see the following warning by the compiler “match cannot be exhaustive”, and you may encounter
scala.MatchError unexpectedly at run time. - They are not compatible with the Javas enum - it’s not very scary if you don’t support the Java API, but if you do, it can be an unexpected disappointment for you.
Overloading with Scala transfers that do not work due to the fact of the same type of transfers after deletion. So, the following snapshot of the code is invalid:
object WeekDays extends Enumeration { val Mon, Tue, Wed, Thu, Fri = Value } object WeekEnds extends Enumeration { val Sat, Sun = Value } object DaysOperations { def f(x: WeekEnds.Value) = "That a weekend" def f(x: WeekDays.Value) = "That a weekday" }
It will throw error: double definition: have the same type after erasure: (x: Enumeration#Value)String . As you can see, scala.Enumeration not user friendly and prefers not to use it, it will make your life easier.
Right approaches: The right approach uses a combination of case object or object with the sealed class:
object WeekDays { sealed trait EnumVal case object Mon extends EnumVal case object Tue extends EnumVal case object Wed extends EnumVal case object Thu extends EnumVal case object Fri extends EnumVal val daysOfWeek = Seq(Mon, Tue, Wed, Thu, Fri) }
In addition, you cannot use a wrapper object to enumerate:
sealed trait Day { def description: String } case object Monday extends Day { val description = "monday is awful" }
Using a third-party library - Enumeratum can also solve the scala.Enumeration problem, it is a type-safe and powerful enumeration implementation and is easy to use and understand.
libraryDependencies ++= Seq( "com.beachape" %% "enumeratum" % enumeratumVersion ) import enumeratum._ sealed trait Day extends EnumEntry object Greeting extends Enum[Greeting] { val values = findValues case object Mon extends Day case object Tue extends Day case object Wed extends Day case object Thu extends Day case object Fri extends Day }
Artem rukavytsia
source share