I need to remove physical field without adding setter. Is it possible? (code for example)
class Example {
public var field(get, null):String;
function get_field() {
trace(field); // src/Example.hx:5: Useless
return "Field";
}
public function new() {
field = "Useless";
trace(field); // src/Example.hx:11: Field
}
static function main() { new Example(); }
}
Memory is allocated to store a physical field, while no memory is allocated to store a non-physical field.
In the OP’s example, field was physical, so Haxe would always allocate room for a string every time someone called new Example(). However, OP wanted to hard-code a value of "Field", stored in the get_field() function, so there was no reason to store anything in field. Changing (get, null) to (get, never) made the field non-physical, meaning the compiler would no longer allocate extra memory for each instance.
From the outside, field still looks and acts like it stores a value, but the underlying memory is more efficient.
I was not aware of the existence of physical fields, thank you very much. Most of my targets are dynamic, and I think this applies more to compiled languages like c or c++, right?
class SampleClass {
public var physicalField:Float = 0;
public var nonPhysicalField(get, never):Float;
public inline function new() {
}
private function get_nonPhysicalField():Float {
return physicalField;
}
}