Object Creation
In this lesson, we will create a rectangle object and study its properties.
We'll cover the following
The Structure
The structure of an object is very similar to that of a record. A typical object contains three components:
Values
These are the properties of the object. They are defined in the object body using the val
keyword. The values of an object cannot be directly accessed from the outside.
Depending on our program, the values of an object can be mutable or immutable.
Public Functions
Public functions are methods which can manipulate and use the object’s values. They can be defined using the pub
keyword.
These functions can be accessed from the outside. They allow an interface between the object and the other parts of the program.
In that sense, public functions can be considered open to the public.
Private Functions
Like their public counterparts, private functions also have access to the object’s values. However, they are hidden from the outside world and cannot be called directly. Instead, only public functions can call the private functions of an object.
Private functions can be defined using the pri
keyword.
Type Definition
So, let’s get started and build a rectangle
object. A good practice is to define the object’s type first, just like we do for records.
For object types, the .
operator has to be used right after the scope of the definition begins. In the type definition, we only mention the names of the public methods and their return types.
Get hands-on with 1400+ tech skills courses.