Prev | Current Page 254 | Next

L. McColl-Sylvester and F. Ponticelli

"Professional haXe and Neko"

A type parameter is a generic placeholder for
a concrete type.
124
Part I: The Core Language
The example can now be re - coded as follows:
class BinaryNode < T >
{
private var content : T;
public var parent : BinaryNode < T > ;
public var leftChild : BinaryNode < T > ;
public var rightChild : BinaryNode < T > ;
public function new (content : T)
{
this.content = content;
}
public function getContent() : T
{
return content;
}
}
On class instantiation a type must be provided in place of T in this way:
var ns : BinaryNode < String > = new BinaryNode < String > (???I??™m a node???);
Another example could be:
var ni : BinaryNode < Int > = new BinaryNode < Int > (7);
Now ns.getContent() will return a value of String type while ni.getContent() will return a value
of Int type.
You can shorten the type declaration, further taking profit from type inference and reduce the code
to this:
var ns = new BinaryNode(???I??™m a node???);
The String type parameter can be omitted in the constructor because the compiler can infer the correct
type from the textual argument.


Pages:
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266