问题
i'm looking for a way to do something like this in Haxe:
function foo(...args)
{
for (arg in args)
{
...
}
}
Someone around here who can help me?
回答1:
Haxe doesn't have rest arguments, mostly because those are untyped by nature, and the language should help going typed to have safest code. Typed code can be checked and also optimized by the compiler. More errors compile-time, less errors run-time.
Still the same result of rest arguments can be somehow achieved in a few ways, depending on what you are looking for; does the function only receive values or also objects?
The most straightforward way is using the Any
type and Reflect
:
function loop(props:Any)
{
for (prop in Reflect.fields(props))
{
trace(prop, Reflect.field(props, prop));
}
}
// usage:
loop({name: "Jerson", age: 31});
You can just use an array with values, therefore you also need to use an array when you use it:
static function loop(values:Array<Any>)
{
for (i in 0...values.length)
{
trace(i, values[i]);
}
}
//usage:
loop(["Jerson", 31]);
If you dislike this array in the implementation, you can also use this wonky function, which I wouldn't advice, but just to give an idea.
function loop<A,B,C,D,E,F>(?prop1:A, ?prop2:B, ?prop3:C, ?prop4:D, ?prop5:E, ?prop6:F)
{
var props:Array<Any> = [prop1,prop2,prop3,prop4,prop5,prop6];
for (i in 0...props.length)
{
trace(i, props[i]);
}
}
// usage:
loop3("Jerson", 31);
Try these examples here: https://try.haxe.org/#Be3b7
There are also macros for rest arguments, which can be nice if you are familiar with macros. Note that this will trace while compiling and doesn't generate the trace in the output source at the moment.
import haxe.macro.Expr;
macro static function loop(e1:Expr, props:Array<Expr>)
{
for (e in props)
{
trace(e);
}
return macro null;
}
// Usage:
loop("foo", a, b, c);
Best advice of course is just don't go dynamic much to keep type-safety, but this should keep you going.
回答2:
If you really need to, there's a way: Reflect.makeVarArgs. This is heavily untyped, so I recommend that you consider using a typed alternative first.
Personally, I would probably only use this for debugging or in code that's already untyped for some other reason.
Example:
static function _foo(args:Array<Dynamic>)
{
return "Called with: " + args.join(", ");
}
static var foo:Dynamic = Reflect.makeVarArgs(_foo);
[...]
trace(foo(1));
trace(foo(1, 2));
trace(foo(1, 3, 3));
(see it in Try Haxe)
来源:https://stackoverflow.com/questions/43465215/variable-number-of-arguments-in-haxe