August 2013
Intermediate to advanced
720 pages
16h 23m
English
You want to use an enumeration (a set of named values that act as constants) in your application.
Extend the scala.Enumeration
class to create your enumeration:
packagecom.acme.app{objectMarginextendsEnumeration{typeMargin=ValuevalTOP,BOTTOM,LEFT,RIGHT=Value}}
Then import the enumeration to use it in your application:
objectMainextendsApp{importcom.acme.app.Margin._// use an enumeration value in a testvarcurrentMargin=TOP// later in the code ...if(currentMargin==TOP)println("working on Top")// print all the enumeration valuesimportcom.acme.app.MarginMargin.valuesforeachprintln}
Enumerations are useful tool for creating groups of constants, such as days of the week, weeks of the year, and many other situations where you have a group of related, constant values.
You can also use the following approach, but it generates about
four times as much code as an Enumeration, most of which you won’t need if
your sole purpose is to use it like an enumeration:
// a much "heavier" approachpackagecom.acme.app{traitMargincaseobjectTOPextendsMargincaseobjectRIGHTextendsMargincaseobjectBOTTOMextendsMargincaseobjectLEFTextendsMargin}
Scala Enumeration class |
Read now
Unlock full access