According to 86% of developers surveyed by Scala, the most “exciting” Scala 3 development is the introduction of enums. Incredibly basic conceptually, enums allow developers to group related, constant values.
Armed with native enums, developers no longer have to rely on extending classes to create an enumeration before it can be imported into their application. Instead, the enum can be built directly into code – far simpler and more elegant from a code perspective.
EXAMPLE:
A basic pizza store application would look like this in Scala 2:
// scala 2.x
sealed trait Topping
caseobject Cheese extends Topping
caseobject Pepperoni extends Topping
caseobject Sausage extends Topping
caseobject Mushrooms extends Topping
caseobject Onions extends Topping
sealed trait CrustSize
caseobject SmallCrustSize extends CrustSize
caseobject MediumCrustSize extends CrustSize
caseobject LargeCrustSize extends CrustSize
sealed trait CrustType
case object RegularCrustType extends CrustType
case object ThinCrustType extends CrustType
case object ThickCrustType extends CrustType
Using Scala 3 and enums, the code is far simpler to write and understand:
// scala 3
enum CrustSize: {
case Small, Medium, Large
}
enum CrustType: {
case Thin, Thick, Regular
}
enum Topping: {
case Cheese, Pepperoni, Olives
}
(Code sample courtesy of Alvin Alexander)
This is a small section of Signify paper; Scala 3 - what to expect.
Download now through the link in the image below.
