Copyright © 2024 Sebastiaan Heins
class
is a master keyword, it is used to create a class definition.
A class is a blueprint for creating objects.
A class can have properties and methods.
Example of a simple class definition:
class Person (string name, int age) {
set self->name = name
set self->age = age
}
make p = Person("John", 30)
do say (p->name) // John
do say (p->age) // 30
The syntax for creating a class is as follows:
1. After the class keyword, you write the name of the class.
2. Write the constructor parameters in parentheses (same as function parameters).
3. A class body, this is enclosed in curly braces.
A class is a blueprint for creating objects.
The object the class creates is called an instance.
In the class you can access the instance with the self
keyword.
Like a regular dictionary, you can set and get properties on the instance with the ->
operator.
A class can have methods.
Methods are functions that are defined inside of a class.
Methods can access the instance with the self
keyword.
Example of a class with a method:
class Person (string name, int age) {
set self->name = name
set self->age = age
implement greet() {
do sayln (`Hello, my name is {self->name} and I am {self->age} years old`)
}
}
make p = Person("John", 30)
do p->greet() // Hello, my name is John and I am 30 years old
The implement master keyword is used to define a method.
The method can be called on the instance with the ->
operator.
Info!
You can't use the implement
master keyword outside of a class.
You can't use the self
keyword outside of a class.
You can't use the return
master keyword inside of a class body.
Although this isn't nativly included in the grammar, it's really easy to implement.
Take a look at the following example:
class Person (string name, int age) {
set self->name = name
set self->age = age
implement greet() {
do sayln (`Hello, my name is {self->name} and I am {self->age} years old`)
}
}
class Employee (string name, int age, string occupation) {
// Inherit from Person
set self += Person(name, age)
set self->occupation = occupation
implement sayOccupation() {
do sayln (`I am a {self->occupation}`)
}
}
make e = Employee("John", 30, "Programmer")
do e->greet() // Hello, my name is John and I am 30 years old
do e->sayOccupation() // I am a Programmer
Since, when you add two objects together, the properties of the right object are added to the left object, you can use this to inherit from another class.
It will add all the missing fields and methods from the parent class to the child class.