- 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.
- DBA攻堅指南:左手Oracle,右手MySQL
- Rust實戰
- Podman實戰
- Microsoft Dynamics GP 2013 Reporting, Second Edition
- Java應用開發技術實例教程
- R Deep Learning Cookbook
- ElasticSearch Cookbook(Second Edition)
- Python商務數據分析(微課版)
- Qt 4開發實踐
- 實戰Python網絡爬蟲
- Neo4j 3.x入門經典
- Mastering Unity 2017 Game Development with C#(Second Edition)
- C語言從入門到精通(第5版)
- Python程序設計案例教程
- JavaScript+jQuery交互式Web前端開發(第2版)