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

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.

主站蜘蛛池模板: 三门县| 安龙县| 寿阳县| 阳东县| 襄城县| 东阿县| 东乌珠穆沁旗| 石台县| 马公市| 靖西县| 东城区| 开鲁县| 中江县| 滦平县| 巧家县| 湘潭市| 曲阳县| 博爱县| 定西市| 凤山市| 喀喇沁旗| 北海市| 阳城县| 松阳县| 宁乡县| 射洪县| 兴宁市| 共和县| 孟村| 巴中市| 福贡县| 交城县| 望谟县| 开平市| 乡城县| 金堂县| 黄陵县| 武清区| 西城区| 蓝田县| 新乡县|