How do I define a property in Ceylon? I know I can write getName and setName functions to get and set a backing variable:
class Circle(shared variable Float radius) {
shared Float getArea() {
return pi * radius ^ 2;
}
shared void setArea(Float area) {
radius = sqrt(area / pi);
}
}
value circle = Circle(4.0);
circle.setArea(10.0);
print(circle.getArea());
But I would like to be able to provide attribute-like access to the property:
value circle = Circle(4.0);
circle.area = 10.0;
print(circle.area);
How do I do this in Ceylon?
Getters are declared like defining a function with no parameter list. The getter body then behaves like a normal function and must return the calculated value of the property.
Setters are declared using the
assignkeyword. The setter body then behaves like a void function, performing whatever mutation of the local environment is appropriate and must not return a value. The incoming value being assigned can be referred to in the body via the name of the property.Unlike most programming languages, properties can be top level members of the package, not just members of a class: