官术网_书友最值得收藏!

Member functions

The first type of function is called member functions. These functions are defined inside a class, object, or interface. A member function is invoked by 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 to take on an a string instance, 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 
      } 
    } 

This code snippet shows two functions that calculate the area of a rectangle and output it to the console. The printArea function takes two parameters, width and height, and uses the calculateArea function to do the math. The first function then outputs the result of the other function.

You will also notice that the calculateArea function uses return, since the value it computes is intended to be used by other functions. The printArea function does not have any meaningful value to return, so we define its return value as Unit.

主站蜘蛛池模板: 慈利县| 桂阳县| 漯河市| 阿拉尔市| 象山县| 洛宁县| 金湖县| 大宁县| 隆尧县| 英吉沙县| 滁州市| 武川县| 尤溪县| 阿拉善盟| 霍林郭勒市| 正宁县| 新津县| 武宁县| 清原| 咸丰县| 安图县| 高雄县| 奉新县| 玛沁县| 怀远县| 嘉峪关市| 开化县| 新化县| 温州市| 丹巴县| 鸡泽县| 绩溪县| 攀枝花市| 屏南县| 德阳市| 玛沁县| 左云县| 南陵县| 北京市| 鄂托克前旗| 衡阳市|