- 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.
推薦閱讀
- Git Version Control Cookbook
- LabVIEW2018中文版 虛擬儀器程序設計自學手冊
- Learning PostgreSQL
- 深度學習經典案例解析:基于MATLAB
- Learn Swift by Building Applications
- 深入淺出DPDK
- Machine Learning With Go
- Qt5 C++ GUI Programming Cookbook
- Mastering ASP.NET Web API
- Managing Windows Servers with Chef
- Learning Java Lambdas
- 軟件自動化測試實戰解析:基于Python3編程語言
- 信息學競賽寶典:基礎算法
- Prezi Cookbook
- Responsive Web Design with HTML5 and CSS3(Second Edition)