Skip to content

Instantly share code, notes, and snippets.

@back2dos
Last active July 28, 2017 09:02
Show Gist options
  • Save back2dos/590eb021c9f1734bdcd1887a552e771d to your computer and use it in GitHub Desktop.
Save back2dos/590eb021c9f1734bdcd1887a552e771d to your computer and use it in GitHub Desktop.
Reference local class as `Self`.
package ;
#if macro
import haxe.macro.Context.*;
class Self {
static public function buildSelf()
return getType(
switch getTypedExpr(typeExpr(macro (function (?pos:haxe.PosInfos) {})())).expr {
case ECall(_, [macro { fileName: $_, lineNumber: $_, className: ${{ expr: EConst(CString(name)) }}, methodName: $_ }]): name;
default: throw 'assert';
}
);
}
#else
@:genericBuild(Self.buildSelf())
class Self {}
#end
@back2dos
Copy link
Author

back2dos commented Jul 28, 2017

Usage example: http://try-haxe.mrcdk.com/#72855

Please note that this does not work across inheritance.

Meaning:

class A {
  public function new() {}
  public function foo():Self return this;
}
class B extends A {}
$type(new B().foo());//yields A

All this type does is to refer to the class itself in the context of the class. The use case for this is to have the class name appear exactly once per class declaration.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment