Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Object initialisations syntax sugar
import haxe.macro.Expr;
import haxe.macro.Context;
using haxe.macro.ExprTools;
class ObjectInit {
macro public static function init( expr:Expr, varsToSet:ExprOf<Dynamic<Dynamic>> ) {
var lines:Array<Expr> = [];
lines.push( macro var __obj_init_tmp = $expr );
switch varsToSet.expr {
case EObjectDecl(fields):
for ( field in fields ) {
var varName = field.field;
var varValue = field.expr;
lines.push( macro __obj_init_tmp.$varName = $varValue );
}
case other: Context.error( 'Expected ${expr.toString()}.init() argument to be an object declaration', expr.pos );
}
lines.push( macro __obj_init_tmp );
return { expr: EBlock(lines), pos: expr.pos };
}
}
using ObjectInit;
class ObjectInitTest {
static function main() {
var person = new Person().init({
name: "Jason",
age: 27,
likes: ["coffee","code"]
});
trace( person.name );
}
}
class Person {
public function new() {}
public var name:String;
public var age:Int;
public var likes:Array<String>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.