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.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.226.120