Combining custom types and functions
Functions can work with values of user-defined types just as much as they work with fundamental data types. Take a look at the following example where the area of a Rectangle is calculated using a function called area.
This way of calculating the area of the rectangle works fine. However, we start to see issues when we have multiple types for which we want to calculate their areas. The following example introduces a second type called Triangle. To avoid naming conflicts, we need to use two different names for the functions that calculate the area of their respective shape.
Admittedly, with just two types in the program, choosing distinct names for the functions is not hard. However, it can become an issue in a larger codebase. To fix this, we can associate the functions directly with their respective type by moving the function inside the body of the type definition.
A function located inside the body of a type is called a method. As you can see, now we can call both methods " area " once again because the name only has to be unique within the type definition, not in the global scope. There is also a difference in how a method is accessed or called. The method is accessed like any attribute of the type via the dot-notation, as can be seen in the following example.
Another difference compared to calling a function is that you don't have to specify the first parameter when calling a method. You are calling the method on the value left of the dot. The language automatically passes that value as the first parameter to the method.
Methods can have multiple parameters just like functions; however, the first parameter always has to be of the same type as the surrounding type. The following example adds the method larger_than to Rectangle, comparing the area of two rectangles.