Stucko
Stucko

Reputation: 65

AS3: Can we skip an optional parameter and assign value to the parameter after the skipped one?

Can we skip an optional parameter and assign value to the parameter after the skipped one?

For example I have a function:

public function Dialog(message:String,title:String="Note",dialogsize:int=99):void
{
}

I can easily call the function with a message and a title:

 Dialog("HELLO","Intro");

Is there a way to skip the title and just pass in the dialogsize? I've tried it but can't make it work:

Dialog("HELLO",,dialogsize);

Is it possible to skip some optional parameters without using (rest) parameter?

Upvotes: 3

Views: 4174

Answers (3)

Mattias
Mattias

Reputation: 3907

I would use a valued object instead of an object to have more control over the contents:

// DialogVO.as
package
{
    public class DialogVO
    {
        public var message : String;
        public var title : String;
        public var size : int;
    }
}

// Test.as
public function createDialog(vo : DialogVO) : void
{
    if(vo.title)
        // write code for title here

    if(vo.message)
        // write code for meassage here

    if(vo.size)
        // write code for size here
}

// test your method
var dialogData : DialogVO = new DialogVO();
    dialogData.message = "This is the message";
    dialogData.size = 92;

createDialog(dialogData);

Upvotes: 1

Lee
Lee

Reputation: 13542

You can pass null, for a "defaulted" parameter, and as3 will use the default value -- same as if you had omitted it completely:

Dialog("HELLO",null,dialogsize);

Edit

I stand corrected -- I could swear that I've done this before, with success... but my tests (and those of @www0z0k also) indicate otherwise. That means that, in order to have the above work as described, you'd need to modify the function's implementation too.

Something like this will do the trick:

public function Dialog(message:String,title:String=null,dialogsize:int=99):void
{
    if(title===null) title = "Note";

}

Upvotes: 6

www0z0k
www0z0k

Reputation: 4434

it's impossible, but you can do something like:

public function Dialog(message:String, optionalArgs: Object):void{
    var title: String = optionalArgs['title'] ? optionalArgs['title'] : 'default value';
    var dialogsize: int =  optionalArgs['dialogsize'] ? optionalArgs['dialogsize'] : 99;
    var smthElse: String =  optionalArgs['smthElse'] ? optionalArgs['smthElse'] : 'another default val';
}

and:
Dialog('msg', {dialogsize: 250, smthElse: 'another value'});

Upvotes: 2

Related Questions