My question is regarding properties in haxe.
If I understand it correctly, if I make property like this
var propertyInt(get, set):Int;
according to haxe documentation it's not really a variable. But I can make it a variable by modifying it this way
@:isVar var propertyInt(get, set):Int;
. Otherwise I need to make two methods:
function get_propertyInt()
return propertyInt;
function set_properyInt(i)
return propertyInt = i;
So my question is: does it matter if I'm using exclusively @:isVar var propertyInt(get, set):Int;
? For example I have more than 5 properties in my class and as you can imagine making this methods for every property could be huge pain in the rear. So what is the best approach?
Here's what the documentation has to say about physical properties (also known as backing fields):
A field is considered to be physical if it is either
- variable
- a property with the read-access or write-access identifier being
default
ornull
- a property with
:isVar
metadata
So you can set up a property that fully consists of calculated values. Think a read-only property giving you the area of a rectangle as a function of width and height, or think of a property that is backed by some other property and just returns/sets width and height in a different unit. Or maybe you just want to name your backing fields differently, say m_width
and m_height
.
The :isVar
is helpful in situations where the property access rules etc. laid out above would let the compiler think that there is no backing field needed. In that case, the code would fail (from the docs again):
// This field cannot be accessed because it
// is not a real variable
public var x(get, set):Int;
function get_x() {
return x;
}
function set_x(x) {
return this.x = x;
}
By adding :isVar
you basically tell the compiler that you absolutely want the backing field. The other option for your particular case would be to use default,default
, in which case the compiler knows there is an automatic backing field required and access should be restricted according to the access level of the property (public
or private
):
public var propertyInt(default, default):Int;
In that case you might also use a variable directly, because the net effect is in essence the same:
public var propertyInt : Int;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With