官术网_书友最值得收藏!

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.
主站蜘蛛池模板: 鸡西市| 五莲县| 大邑县| 玉龙| 海原县| 招远市| 开平市| 乐山市| 望江县| 盐源县| 固始县| 瓦房店市| 县级市| 巴林左旗| 江孜县| 普安县| 诸暨市| 四子王旗| 清流县| 邵东县| 稷山县| 泸溪县| 廊坊市| 乌拉特后旗| 波密县| 广宗县| 沂水县| 新兴县| 高清| 拜泉县| 石嘴山市| 闽清县| 项城市| 禹州市| 安仁县| 城口县| 新兴县| 利川市| 湟源县| 彭水| 闵行区|