Skip to content
Kavachकवच

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
methods.kav: Kavach code, then what running it prints
  • r.area() calls the method on r, which inside it is self.
  • A function without self, like square, 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!
extend.kav: Kavach code, then what running it prints