Methods
Also known as: method member function self this extend extension impl
● Intermediate4 minBefore this: RecordsSpec 2.5
A method is a function that belongs to a type, written inside it. self is the value it is called on.
type Rect {
width: Float
height: Float
fn area(self) -> Float {
self.width * self.height
}
fn square(size: Float) -> Rect {
Rect(width: size, height: size)
}
}
fn main() {
const r = Rect(width: 3.0, height: 2.0)
print(r.area())
print(Rect.square(4.0).area())
}The program ran and printed:
kavach run methods.kav
6.016.0
r.area()calls the method onr, which inside it isself.- A function without
self, likesquare, is called on the type:Rect.square(4.0).
Methods for any type
extend adds methods to a type you didn't write, even a built-in one:
extend String {
fn shout(self) -> String {
self.upper() + "!"
}
}
fn main() {
print("namaste".shout())
}The program ran and printed:
kavach run extend.kav
NAMASTE!