Haxe property - getters and setters against @: isVar

My question is about properties in haxe. If I understand correctly, if I create such a property var propertyInt(get, set):Int; according to haxe documentation this is not really a variable. But I can make this a variable by changing 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 use exclusively @:isVar var propertyInt(get, set):Int; ? For example, I have more than 5 properties in my class, and, as you can imagine, for these methods for each property there can be a huge pain in the back. So what is the best approach?

+5
source share
1 answer

Here is what the documentation has to say about physical properties (also called fallback fields ):

A field is considered physical if either

  • variable
  • property with read access identifier or access identifier set to default or null
  • metadata property :isVar

So, you can set up a property that consists entirely of calculated values. Think of a read-only property giving you the area of ​​the rectangle as a function of width and height, or think of properties that are supported by some other property, and simply return / set the width and height in another block. Or maybe you just want to name your support fields differently, say m_width and m_height .

:isVar is useful in situations where the rules for accessing resources, etc., described above, allow the compiler to think that there is no necessary support field. In this case, the code will fail (from the documents 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 a support field. Another option for your specific case would be to use default,default , in which case the compiler knows that an automatic support field is required, and access should be limited according to the access level of the property ( public or private )

 public var propertyInt(default, default):Int; 

In this case, you can also use the variable directly, because the network effect is essentially the same:

 public var propertyInt : Int; 
+10
source

Source: https://habr.com/ru/post/1211032/


All Articles