🚧 Status: Function overloading is not implemented yet.
Composite types may contain functions. Just like in the initializer, the special constant self refers to the composite value that the function is called on.
// Declare a structure named "Rectangle", which represents a rectangle
// and has variable fields for the width and height.
//
pub struct Rectangle {
pub var width: Int
pub var height: Int
init(width: Int, height: Int) {
self.width = width
self.height = height
}
// Declare a function named "scale", which scales
// the rectangle by the given factor.
//
pub fun scale(factor: Int) {
self.width = self.width * factor
self.height = self.height * factor
}
}
let rectangle = Rectangle(width: 2, height: 3)
rectangle.scale(factor: 4)
// `rectangle.width` is `8`
// `rectangle.height` is `12`
Functions support overloading.
// Declare a structure named "Rectangle", which represents a rectangle
// and has variable fields for the width and height.
//
pub struct Rectangle {
pub var width: Int
pub var height: Int
init(width: Int, height: Int) {
self.width = width
self.height = height
}
// Declare a function named "scale", which independently scales
// the width by a given factor and the height by a given factor.
//
pub fun scale(widthFactor: Int, heightFactor: Int) {
self.width = self.width * widthFactor
self.height = self.height * heightFactor
}
// Declare a another function also named "scale", which scales
// both width and height by a given factor.
// The function calls the `scale` function declared above.
//
pub fun scale(factor: Int) {
self.scale(
widthFactor: factor,
heightFactor: factor
)
}
}