Optional Arguments
Some function parameters can be made optional by using a question mark ? before the parameter name :
class Test { static function foo( x : Int, ?y : Int ) { trace(x+","+y); } static function main() { foo(1,2); // trace 1,2 foo(3); // trace 3,null } }
Default values
When not specified, an optional parameter will have the default value null. It's also possible to define another default value, by using the following syntax :
static function foo( x : Int, ?y : Int = 5 ) { // ... }
Thanks to type inference, you can also shorten the syntax to the following :
static function foo( x : Int, y = 5 ) { // ... }
Ordering
Although it is advised to put optional parameters at the end of the function parameters, you can use them in the beginning or in the middle also.
Also, optional parameters are independent in haXe. It means that one optional parameter can be used without providing a previous one :
function foo( ?x : A, ?y : B ) { } foo(new A()); // same as foo(new A(),null); foo(new B()); // same as foo(null, new B()); foo(); // same as foo(null,null); foo(new C()); // compile-time error foo(new B(),new A()); // error : the order must be preserved
However, such usages of optional arguments could be considered quite advanced.
Enum Values
Enums' values can not be used as default values for optional arguments. See Enums for more information.
Warning
Optional Arguments are a compile-time feature and therefore their behavior may vary on different platforms when used on Dynamic calls or with Reflection.
«« Properties | Conditional Compilation »»