Next to variables, properties are the second option for dealing with data on a class. Unlike variables, however, they offer more control of which kind of field access should be allowed and how it should be generated. Common use cases include:
When dealing with properties, it is important to understand the two kinds of access:
Define: Read Access
A read access to a field occurs when a right-hand side field access expression is used. This includes calls in the form of
obj.field()
, wherefield
is accessed to be read.Define: Write Access
A write access to a field occurs when a field access expression is assigned a value in the form of
obj.field = value
. It may also occur in combination with read access for special assignment operators such as+=
in expressions likeobj.field += value
.
Read access and write access are directly reflected in the syntax, as the following example shows:
class Main { public var x(default, null):Int; static public function main() {} }
For the most part, the syntax is similar to variable syntax, and the same rules indeed apply. Properties are identified by
(
after the field name,default
),,
separatingnull
))
.The access identifiers define the behavior when the field is read (first identifier) and written (second identifier). The accepted values are:
default
: Allows normal field access if the field has public visibility, otherwise equal to null
access.null
: Allows access only from within the defining class.get
/set
: Access is generated as a call to an accessor method. The compiler ensures that the accessor is available.dynamic
: Like get
/set
access, but does not verify the existence of the accessor field.never
: Allows no access at all.Define: Accessor method
An accessor method (or short accessor) for a field named
field
of typeT
is a getter namedget_field
of typeVoid->T
or a setter namedset_field
of typeT->T
.Trivia: Accessor names
In Haxe 2, arbitrary identifiers were allowed as access identifiers and would lead to custom accessor method names to be admitted. This made parts of the implementation quite tricky to deal with. In particular,
Reflect.getProperty()
andReflect.setProperty()
had to assume that any name could have been used, requiring the target generators to generate meta-information and perform lookups.We disallowed these identifiers and went for the
get_
andset_
naming convention which greatly simplified implementation. This was one of the breaking changes between Haxe 2 and 3.