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

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.

主站蜘蛛池模板: 大安市| 方正县| 晋江市| 沛县| 密云县| 木兰县| 兴义市| 兴山县| 皋兰县| 英山县| 承德市| 郴州市| 彭水| 和顺县| 惠来县| 墨玉县| 农安县| 获嘉县| 临沧市| 鸡东县| 定安县| 阿图什市| 潍坊市| 惠州市| 嘉黎县| 城固县| 绥宁县| 乐陵市| 喀什市| 富蕴县| 新晃| 宁强县| 阳江市| 南靖县| 义乌市| 方山县| 同仁县| 鹤峰县| 威宁| 高安市| 阿拉善右旗|