Prev | Current Page 221 | Next

L. McColl-Sylvester and F. Ponticelli

"Professional haXe and Neko"


class Main
{
static function main()
{
var sample = new NullParameterSample();
trace(sample.cube(7));
trace(sample.cube(null));
}
}
class NullParameterSample
{
public function new () { }
public function cube(n : Float) {
return n*n*n;
}
}
The method cube accepts a mandatory float parameter. If tested with value 7 , the result is 343 as
expected but if tested with null , which is a perfectly valid value on every platform but Flash 9, the
result varies.
The best way to avoid inconsistencies is to verify the function parameters before using them and throw
an error (error handling is covered in Chapter 7 ) or fallback to a common result.
106
Part I: The Core Language
The preceding example can be corrected this way to obtain a consistent result on every platform.
public function cube(n : Float)
{
return if(n == null)
null;
else
n*n*n;
}
Optional Arguments
Every function argument admits an optional question mark ? prefix. If present, it indicates that the
argument is optional and it can be omitted when the function is invoked.


Pages:
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233