haxe icon indicating copy to clipboard operation
haxe copied to clipboard

@:structInit class properties cannot be marked optional on some targets

Open nspitko opened this issue 3 years ago • 0 comments
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

nspitko avatar Mar 30 '22 08:03 nspitko