ActionScript3 does not support method overloading, but why do you want to overload methods?
In my opinion there are two answers:
- You want to pass the same method different amount of parameters
- You want to have methods with same name but different behavior
In first case AS3 provides you the feature of default parameter values:
function foo(var a : String, var i : int = 0): void{ for(;i<=0 ; i++){ trace(a); } } |
So you can call method foo with one parameter “foo(‘hello’)” or with two “foo(‘hello’, 2)”
Let’s talk about the second case: same name different behavior.
In this case you can use namespaces.
package my { public class NamespaceExamp { namespace NS1; namespace NS2; NS1 function foo() : void { } NS2 function foo() : void { } } } |
The interesting part of namespaces is also that those are not declaration but URI based (like in XML).
Have a look at this example:
package my { public class NamespaceExamp { namespace NS1 = "myNS"; namespace NS2 = "myNS"; NS1 function foo() : void { } NS2 function foo() : void { } } } |
In this case foo is a duplicate method and it doesn’t matter that we declared two namespaces, their URIs are same so both foo declarations are in the same namespace. BTW if you don’t declare URI explicitly as in the first namespace example than the runtime will generate a namespace by the location of declaration (complicated stuff).
Another interesting fact is that the keyword “public” is also a namespace, but with empty URI.
So this is also a duplicate declaration:
package my { public class NamespaceExamp { namespace NS1 = ""; NS1 function foo() : void { } public function foo() : void { } } } |
Hey Max
This is very interessting… I created this example:
var builder : SomeBuilder = new SomeBuilder();
builder.buildRectangle(0, 0, 100, 100);
builder.byPoint::buildRectangle(new Point(0, 0), new Point(100, 100));
builder.byRectangle::buildRectangle(new Rectangle(0, 0, 100, 100));
…it works
Great idea!
Hey Max,
awesome! Well done. Thanks a lot for pushing FDT
.
cheers Carlo
I am glad to help