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

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.
主站蜘蛛池模板: 自贡市| 岐山县| 奉节县| 远安县| 年辖:市辖区| 武清区| 临清市| 葫芦岛市| 新乡县| 昌图县| 昌图县| 南部县| 化州市| 富民县| 峨眉山市| 万年县| 新竹市| 屯昌县| 淮安市| 德令哈市| 安庆市| 肇源县| 和硕县| 淳安县| 休宁县| 灌南县| 东海县| 龙井市| 韶关市| 安徽省| 米易县| 绥阳县| 抚宁县| 济南市| 蓬溪县| 翁牛特旗| 海南省| 元谋县| 铁岭市| 吴旗县| 安平县|