- 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.
- C#高級編程(第10版) C# 6 & .NET Core 1.0 (.NET開發經典名著)
- AngularJS Testing Cookbook
- GraphQL學習指南
- Mastering Entity Framework
- Spring+Spring MVC+MyBatis從零開始學
- Domain-Driven Design in PHP
- Python 3.7從入門到精通(視頻教學版)
- Python編程:從入門到實踐(第3版)
- C語言程序設計實訓教程與水平考試指導
- C指針原理揭秘:基于底層實現機制
- Oracle Database XE 11gR2 Jump Start Guide
- SQL Server on Linux
- C/C++程序設計教程
- C#編程魔法書
- Mastering Assembly Programming