views:

287

answers:

2

If a constructor takes its parameters as a vararg (...) it seems to be impossible to create a subclass that will just pass on that vararg to the superclass.

There is a related question with fix for this same situation for normal functions: Wrapping a Vararg Method in ActionScipt but I cannot get that to work with a super call.

base class:

public class Bla
{
    public function Bla(...rest)
    {
        trace(rest[0]); // trace the first parameter
    }

}

subclass:

public class Blie extends Bla
{
    public function Blie(...rest)
    {
        // this is not working, it will 
        // pass an array containing all 
        // parameters as the first parameters
        super(rest); 
    }

}

if I now call

        var b1 = new Bla('d', 'e');
        var b2 = new Blie('a', 'b', 'c');

I get the output

d
a,b,c

And I want it to print out:

d
a

Aside from actually moving the handling of the parameters to the subclass or shifting it off to a separate initializer method, does anyone know how to get the super call right?

A: 

There's unfortunately no way to call the super constructor with ... args. If you remove the super() call, it will be called by the compiler (with no arguments). arguments is also not accessible from constructors.

If you can change the method signatures, you modify the arguments to accept an Array rather than ... args. Otherwise, as you mentioned, you could move it into an initializer method.

Richard Szalay
Hmm, not the answer I was hoping for, but thanks for confirming my suspicions.
Simon Groenewolt
A: 

lol, remember when eval was good coding practice? we would do something like this: eval("super("+rest+");");

SparK