Book Image

haXe 2 Beginner's Guide

5 (1)
Book Image

haXe 2 Beginner's Guide

5 (1)

Overview of this book

Table of Contents (21 chapters)
haxe 2
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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:

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