Kotlin Functions


Kotlin Functions

A function is a unit of code that performs a specific function. In programming, the function divides the code into smaller modules, which makes the program more manageable.

Therefore, the function avoids duplication of the code and makes the code more reusable. In Kotlin, there are two types of functions:

  • The Standard Library Function
  • The User-defined Function

Standard Library Function

In Kotlin, the standard library has various built-in functions already defined and available for use. We can pass arguments as needed and call them. In the following program, we will use the built-in functions arrayOf (), sum (), and println (). The function arrayOf () requires some arguments, such as integers, doubles, etc., to create an array, and we can find the sum of all the elements using the sum () without argument.

List of different standard library functions and their uses -

head

  • sqrt () - Used to calculate the square value of a number.
  • Print () - Used to print a message to the standard output.
  • rem () - to find the remainder when dividing one number by another.
  • toInt () - to convert a number to an integer.
  • readline () - to read standard input.
  • compareTo () - to compare two numbers and return the Boolean value.

User-Defined Function

A function defined by the user is called a user-defined function. As we know, we need to define a function to divide an extensive program into smaller modules. Each defined function has its characteristics, such as the function name, the function's return type, and the number of parameters transferred to the function.

Creating User-Defined Function

In Kotlin, the function can be declared above, and you do not have to create a class to hold a function, which we use to do in other languages, such as Java or Scala. fun- For defining a function.

  • fun_name - The name of the function used to call the function later.
  • a: data_type - Here, a passes an argument and specifies the argument's data type, such as data_type integer or string.
  • Return_type - Specify the data value return type by function.

User-Defined Function Call

It is used to create a function to perform a specific task. Whenever it is called a function, it exits the current section of the program code and starts executing the function. Flow-control of a function is as follows:

  • The program displays the line containing a function call.
  • When a function is called, control is transferred to that function.
  • All instructions in the action are executed one by one.
  • Control is only transferred back when the function reaches the closing braces or return statement.
  • Any data provided by the function is used in place of the function on the actual line of code.