[haXe] Optional parameters

Michael Florentin mflorentin at laerdal.dk
Mon Apr 10 12:58:50 CEST 2006


The Action Script flash API often uses optional method parameters.  For 
example String.substr has an optional length parameter.  However 
std.String.substr in haXe is declared as:
   function substr( pos : Int, len : Int ) : String;
This suggests, that I am forced to come up with a value for len, even if 
I just want to get the remainder of the string.  Of course, it's not a 
big deal in this case but myString.substr(7) is prettier than 
myString.substr(7, myString.length - 7) and there might be other places 
in the API where it's more relevant.

As far as I can see, haXe does not support optional parameters.  I did, 
however, manage to access the one-parameter version of substr by using:
   var myString : String = "Hello world";
   var sub : Int->String = untyped myString.substr;
   trace(sub(5));
This is hardly beautiful - are there any better ways to do it?

Another thing I discovered was that you can't mix proper methods into 
extern class declarations.  Following the considerations above about 
substr, I decided to add a single parameter substr-method to std/String.hx:
   public function substr1(pos : Int) : String {
     var sub : Int->String = untyped s.substr;
     return sub(pos);
   }
This compiles fine but when I try:
   trace("Hello world".substr1(5));
I get an "undefined".  It seems  that when a class is declared "extern", 
all methods are interpreted as declarations - even when they have a body 
- and calling substr1 ends up trying to access a substr1 member in the 
underlying flash class.  A little experimentation reveals that the body 
is parsed but not typed and never reached.

I think proper methods would be nice to have in extern classes, ie. if 
you need to do a bit of marshaling.


Michael Florentin




More information about the Haxe mailing list