- Learn Kotlin Programming(Second Edition)
- Stephen Samuel Stefan Bocutiu
- 234字
- 2021-06-24 14:13:35
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.
- Learning Neo4j
- C++面向對象程序設計(第三版)
- 微信公眾平臺與小程序開發:從零搭建整套系統
- Java 開發從入門到精通(第2版)
- Learning Apache Kafka(Second Edition)
- Interactive Applications Using Matplotlib
- Visual C++應用開發
- PhpStorm Cookbook
- Kali Linux Wireless Penetration Testing Beginner's Guide(Third Edition)
- Python算法從菜鳥到達人
- PHP+Ajax+jQuery網站開發項目式教程
- Building Serverless Web Applications
- 3ds Max 2018從入門到精通
- MongoDB Administrator’s Guide
- Kotlin程序員面試算法寶典