Prev | Current Page 268 | Next

L. McColl-Sylvester and F. Ponticelli

"Professional haXe and Neko"

haXe is not limited to that: enum s are a first
class type definition and represent a type with a fixed set of constructors (zero or more) where
constructors can also have arguments.
The correct syntax for enum is illustrated in Figure 5 - 8 .
enum Name
{
firstConstructor;
otherConstructor(a1 : Type, ?a2 : Type);
}
constructor without
arguments
arguments can be
optional
constructor with
arguments
Figure 5-8
The enum name follows the same convention of class names.
In their simplest form, they are adept at restricting a selection to a certain set of values:
class Main
{
static function main()
{
trace(ByteUnitTools.humanize(1100, Kilobyte)); // trace ???1.07 megabyte(s)???
}
}
135
Chapter 5: Delving Into Object-Oriented Programming
enum ByteUnit
{
Byte;
Kilobyte;
Megabyte;
}
class ByteUnitTools
{
public static function getBytes(unit : ByteUnit) : Int
{
return switch(unit)
{
case Byte: 1;
case Kilobyte: 1024;
case Megabyte: 1024 * 1024;
}
}
public static function humanize(value : Int, unit : ByteUnit) : String
{
var bytes = getBytes(unit) * value;
return if(bytes < = getBytes(Kilobyte))
bytes + ??? byte(s)???
else if(bytes < = getBytes(Megabyte))
round(bytes / getBytes(Kilobyte)) + ??? kilobyte(s)???
else
round(bytes / getBytes(Megabyte)) + ??? megabyte(s)???;
}
private static function round(value : Float)
{
return Math.


Pages:
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280