10.26. Creating and Using Enumerations
Problem
You want to use an enumeration (a set of named values that act as constants) in your application.
Solution
Extend the scala.Enumeration
class to create your enumeration:
package
com.acme.app
{
object
Margin
extends
Enumeration
{
type
Margin
=
Value
val
TOP
,
BOTTOM
,
LEFT
,
RIGHT
=
Value
}
}
Then import the enumeration to use it in your application:
object
Main
extends
App
{
import
com.acme.app.Margin._
// use an enumeration value in a test
var
currentMargin
=
TOP
// later in the code ...
if
(
currentMargin
==
TOP
)
println
(
"working on Top"
)
// print all the enumeration values
import
com.acme.app.Margin
Margin
.
values
foreach
println
}
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" approach
package
com.acme.app
{
trait
Margin
case
object
TOP
extends
Margin
case
object
RIGHT
extends
Margin
case
object
BOTTOM
extends
Margin
case
object
LEFT
extends
Margin
}
See Also
Scala Enumeration class |
Get Scala Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.