Time for action – Naming Anonymous Types

We've already talked about Anonymous Types; with typedefs it is possible to give them a name. This avoids the need to rewrite the complete type definition each time you want to make reference to an anonymous type.

Imagine that we have the following code:

class Greetings
{
   public function new()
   {}
   
   public function sayHiTo(obj : {name : String})
   {
      trace("Hi " + obj.name);
   }
   
   public static function main()
   {
      var paul = {name : "Paul"};
      var d = new Greetings();
      d.sayHiTo(paul);
   }
}

And that we want to rewrite it so that we don't have to rewrite the definition of {name: String} everywhere but instead use the HasName name to refer to it.

We are simply going to write the definition for our type and use it where needed: ...

Get haXe 2 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.