- Kotlin Programming By Example
- Iyanu Adelekan
- 284字
- 2021-08-27 20:00:09
Declaring functions
Functions are declared with the fun keyword. The following is a simple function definition:
fun printSum(a: Int, b: Int) {
print(a + b)
}
The function simply prints the sum of two values that have been passed as arguments to it. Function definitions can be broken down into the following components:
- A function identifier: The identifier of a function is the name given to it. An identifier is required to refer to the function if we wish to invoke it later on in a program. In the preceding function declaration, printSum is the identifier of the function.
- A pair of parentheses containing a comma-separated list of the arguments being passed as values to the function: Values passed to a function are called arguments of the function. All arguments passed to the function must have a type. The type definition of an argument follows a semicolon placed after the argument name.
- A return type specification: Return types of functions are specified similarly to the way the types of variables and properties are. The return type specification follows the last parenthesis and is done by writing the type after a semicolon.
- A block containing the body of the function.
Observing the preceding function, it may appear that it has no return type. This is not true, the function has a return type of Unit. A unit return type need not be explicitly specified. The function might as well be declared as follows:
fun printSum(a: Int, b: Int): Unit {
print(a + b)
}
An identifier is not required for a function. Functions that do not possess an identifier are called anonymous functions. Anonymous functions are present in Kotlin in the form of lambdas.
推薦閱讀
- Cocos2d Cross-Platform Game Development Cookbook(Second Edition)
- HoloLens Beginner's Guide
- AWS Serverless架構:使用AWS從傳統部署方式向Serverless架構遷移
- NLTK基礎教程:用NLTK和Python庫構建機器學習應用
- Learning Apache Mahout Classification
- C# 8.0核心技術指南(原書第8版)
- Mastering Unity 2D Game Development(Second Edition)
- Mastering Xamarin.Forms(Second Edition)
- Web前端應用開發技術
- Arduino機器人系統設計及開發
- Android移動應用項目化教程
- 例說FPGA:可直接用于工程項目的第一手經驗
- Python高性能編程(第2版)
- CryENGINE Game Programming with C++,C#,and Lua
- Learning iOS Penetration Testing