haxe
haxe copied to clipboard
@:structInit class properties cannot be marked optional on some targets
trafficstars
When marking a class as @:structInit, "non-real" properties are required during creation.
Marking the property with @:optional will work around the issue for some targets, but not others. Notably, Hashlink will throw a runtime exception, and Eval will give you a diferent, more exciting compiler error.
Try.haxe url: https://try.haxe.org/#AE0CAbd0
full example, for posterity:
@:structInit
class StructTest
{
public var normalVar: Int = 5;
@:optional
public var prop(get, set): Int;
public function get_prop()
{
return 10;
}
public function set_prop(v)
{
normalVar = 10;
return v;
}
}
class Test {
static function main() {
var empty: StructTest = {};
trace( empty.prop );
}
}
JS/Neko: Works.
HL: Compiles, throws an exception during execution: StructTest does not have field prop
Eval: Fails to compile: Field index for prop not found on prototype StructTest