Optional Arguments
Some function parameters can be made optional by using a question mark before the parameter name or by providing a default value.
- Providing a default value simply makes the parameter optional.
- Explicitly adding a question mark also implies nullability
class Test { static function foo( x:Int, ?y:Int, z:String="hello" ) { trace(x + "," + y + "," + z); } static function main() { foo(1, 2, "world"); // 1,2,world foo(3); // 3,null,hello } }
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, z:String="hello" ) { // ... }
Thanks to type inference, you can also shorten the syntax to the following :
static function foo( x:Int, y=5, z="hello" ) { // ... }
Nullability
When not specified, an optional parameter will have the default value
null but on static platforms (Flash, CPP, Java, C#) null can't be used as basic type. On those platforms the following function definition:static function foo( ?x:Int ) {
will be compiled as:
static function foo( ?x:Null<Int>) {
Considering the following function:
static function foo( x=1 ) {
it cannot be called with foo(null); unless you add a question mark :
static function foo( ?x=1 ) {
or add type information:
static function foo( x:Null<Int>=1 ) {
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 »»