Prev | Current Page 265 | Next

L. McColl-Sylvester and F. Ponticelli

"Professional haXe and Neko"


class RandomSequence
{
private var letters : Int;
private var counter : Null < Int > ;
public function new(letters : Int)
{
this.letters = letters;
}
(continued)
132
Part I: The Core Language
public function hasNext() : Bool
{
if(counter == null)
{
// the iterator has to be initialized
counter = 0;
}
if(counter < letters)
{
return true;
} else {
// before returning false, the counter variable must
// be reset in case the instance has to be used again
counter = null;
return false;
}
}
public function next() : String
{
counter++;
return Std.chr(Std.int(Math.random() * 26)+ 65);
}
}
The code doesn ??™ t declare explicitly that it is implementing the Iterator typedef . This implicitly
happens because the class defines the correct methods. The class is used like this:
class Main
{
static function main()
{
var sequence = new RandomSequence(10);
for(letter in sequence)
{
trace(letter);
}
}
}
The example will trace ten times a random letter.
In practice what haXe does behind the scene is transforming the for(letter in sequence)
declaration in:
while(sequence.


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