Member functions
The first type of functions is called member functions. These functions are defined inside a class, object, or interface. A member function is invoked using the name of the containing class or object instance with a dot, followed by the function name and the arguments in parentheses. For example, to invoke a function called take on an instance of a string
, we do the following:
val string = "hello" val length = string.take(5)
Member functions can refer to themselves and they don't need the instance name to do this. This is because function invocations operate on the current instance, and they are referred to as the following:
object Rectangle { fun printArea(width: Int, height: Int): Unit { val area = calculateArea(width, height) println("The area is $area") } fun calculateArea(width: Int, height: Int): Int { return width * height } } ...