Remove physical field

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(); }

Perhaps I’m misunderstanding your needs, but have you tried the never keyword?

public var field(get, never):String;
1 Like

Given the trace results you provided, it seems you want the default behavior?

Thank you, this is what I needed. I did not even suspect that never exists since it is not on the Rules for getter and setter page.

It’s listed on the parent page and the common access modifier page instead. :slight_smile:

1 Like

Can someone explain me what the question was? I still do t get it

They did not want to have a setter method associated with their property.

They wanted to know how to make a non-physical field.

Define: Physical field

A field is considered to be physical if it is either

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?

No, it applies to any target that supports class instances. (Which is to say, all of them.)

For instance, consider this code sample:

class SampleClass {
  public var physicalField:Float = 0;
  public var nonPhysicalField(get, never):Float;
  public inline function new() {
  private function get_nonPhysicalField():Float {
		return physicalField;

When compiled to JS, it produces the following:

class SampleClass {
	constructor() {
		this.physicalField = 0;
	get_nonPhysicalField() {
		return this.physicalField;

Haxe only sets this.physicalField, which means the browser only has to make space for one value, rather than two.