Prev | Current Page 260 | Next

L. McColl-Sylvester and F. Ponticelli

"Professional haXe and Neko"

This is a fast and effective way to implement a hash table that makes use of
the dot syntax.
var table : Dynamic < String > = cast Reflect.empty();
table.a = ???A???; // works just fine
table.b = 1; // throws a compilation error
128
Part I: The Core Language
Finally a class can implement Dynamic with a type parameter. In this case every field explicitly defined
in the class will maintain its own type, while all the others will have the type of the specified class
parameter.
When a class implements Dynamic , all the derived classes will inherit Dynamic , too. In case one or more
classes implement Dynamic with a class parameter, the last declared in the chain will be the effectively
used one.
Typedef
Typedef is a construct for defining types that are used for type checking of anonymous types. Typedef
declarations must use the following syntax:
typedef Name = typedeclaration
Where Name must follow the same rules exposed for class names and typedeclaration is the signature
of the type definition.
The most common use of typedef is to give a formal representation to anonymous objects:
typedef Color = { r: Int, g: Int, b: Int}
Used like this:
var white : Color = { r: 255, g: 255, b: 255 };
The typedef can also be used to define other types, such as functions or shortcuts to existing definitions:
typedef GenericFunction < T > = Void - > T
typedef IntArray = Array < Int >
typedef P = Person
typedef TS = ThreeState
enum ThreeState
{
Checked;
Unchecked;
Indeterminated;
}
class Person
{
public var name : String;
public function new() { }
}
When declaring the type of an anonymous object, you have two syntax possibilities:
typedef A = {
var x : Float;
var y : Float;
}
129
Chapter 5: Delving Into Object-Oriented Programming
typedef B = {
x : Float,
y : Float
}
In this case, the declarations are equivalents; but you can see the difference with a typedef that contains
at least a function definition:
typedef A = {
function say(text : String) : String;
}
typedef B = {
say : String - > String
}
In this case, the two are almost identical with the only difference being that the function argument is
named in the first declaration and anonymous in the second.


Pages:
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272