Anonymous objects

Anonymous objects are objects that are of an unnamed type ("Anonymous Type"). They are made of a list of fields and their associated values. For example, here is how we can create one:

var obj = {id : 1, name : "Benjamin"};

Although the type of this object doesn't have a name, obj is still fully typed as {id :Int, name : String}. This is an anonymous type.

This is sometimes useful, if there is a type that you are not going to use a lot of time. By the way, this variable could be declared this way:

var obj : {id : Int, name : String};

Duck typing

Duck typing makes reference to an old cliché of "if it walks and talks like a duck, then it's a duck". In fact, we can use anonymous types to say that we want something that has at least some fields.

The following is an example:

class TestAnonymous
{
public var name : String;
public function new(name : String)
{
this.name = name;
}
public static function main(): Void
{
var m;
sayHello(new TestAnonymous("Benjamin"));
}
public static function sayHello(obj : {name : String})
{
trace("Hello " + obj.name);
}
}

In this example, the sayHello function wants an object as a parameter that will have a field name of type String. The TestAnonymous instance satisfies this constraint and therefore, it can be given as a parameter to the sayHello function.

This can be particularly helpful when writing helper functions, in order to not become too rigid on the typing of objects. With this, your typing is more oriented towards how objects behave than towards what they are.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.218.45