Concepts of Programming Languages

(Sean Pound) #1
6.4 User-Defined Ordinal Types 257

from the context of its appearance. For example, if an overloaded literal
and an enumeration variable are compared, the literal’s type is resolved to
be that of the variable. In some cases, the programmer must indicate some
type specification for an occurrence of an overloaded literal to avoid a com-
pilation error.
Because neither the enumeration literals nor the enumeration variables
in Ada are coerced to integers, both the range of operations and the range of
values of enumeration types are restricted, allowing many programmer errors
to be compiler detected.
In 2004, an enumeration type was added to Java in Java 5.0. All enumera-
tion types in Java are implicitly subclasses of the predefined class Enum. Because
enumeration types are classes, they can have instance data fields, constructors,
and methods. Syntactically, Java enumeration type definitions appear like those
of C++, except that they can include fields, constructors, and methods. The
possible values of an enumeration are the only possible instances of the class.
All enumeration types inherit toString, as well as a few other methods. An
array of the instances of an enumeration type can be fetched with the static
method values. The internal numeric value of an enumeration variable can
be fetched with the ordinal method. No expression of any other type can be
assigned to an enumeration variable. Also, an enumeration variable is never
coerced to any other type.
C# enumeration types are like those of C++, except that they are never
coerced to integer. So, operations on enumeration types are restricted to those
that make sense. Also, the range of values is restricted to that of the particular
enumeration type.
In ML, enumeration types are defined as new types with datatype dec-
larations. For example, we could have the following:


datatype weekdays = Monday | Tuesday | Wednesday |
Thursday | Friday


The types of the elements of weekdays is integer.
F# has enumeration types that are similar to those of ML, except the
reserved word type is used instead of datatype and the first value is preceded
by an OR operator (|).
Interestingly, none of the relatively recent scripting kinds of languages
include enumeration types. These include Perl, JavaScript, PHP, Python,
Ruby, and Lua. Even Java was a decade old before enumeration types
were added.


6.4.1.2 Evaluation


Enumeration types can provide advantages in both readability and reliabil-
ity. Readability is enhanced very directly: Named values are easily recognized,
whereas coded values are not.

Free download pdf