Functions

Functions

In Kotlin, functions are used to encapsulate a piece of behavior that can be executed multiple times. Functions can accept input parameters, return values, and provide a way to encapsulate complex logic into reusable blocks of code.
function is a unit of code that performs a special task. In programming, function is used to break the code into smaller modules which makes the program more manageable.
fun sum(a: Int, b: Int): Int { return a + b }
 
  • Standard library function
  • User-defined function

Kotlin standard library function –

In Kotlin, there are different number of built-in functions already defined in standard library and available for use. We can call them by passing arguments according to requirement. In below program, we will use built-in functions arrayOf()sum() and println() The function arrayOf() require some arguments like integers, double etc to create an array and we can find the sum of all elements using sum() which does not require any argument.
fun main(args: Array<String>) { var sum = arrayOf(1,2,3,4,5,6,7,8,9,10).sum() println("The sum of all the elements of an array is: $sum") } // Output: The sum of all the elements of an array is: 55
 
In below program, we will use rem() to find the remainder.
fun main(args: Array<String>) { var num1 = 26 var num2 = 3 var result = num1.rem(num2) println("The remainder when $num1 is divided by $num2 is: $result") } // output: he remainder when 26 is divided by 3 is: 2
 
The list of different standard library functions and their use –
  • sqrt() – Used to calculate the square root of a number.
  • print() – Used to print a message to standard output.
  • rem() – To find the remainder of one number when divided by another.
  • toInt() – To convert a number to integer value.
  • readline() – Used for standard input.
  • compareTo() – To compare two numbers and return boolean value.
 

Kotlin user-defined function –

A function which is defined by the user is called user-defined function. As we know, to divide a large program in small modules we need to define function. Each defined function has its own properties like name of function, return type of a function, number of parameters passed to the function etc
 

⇒ Functions and its different flavors:-

→ Creating user-defined function-

In Kotlin, function can be declared at the top, and no need to create a class to hold a function, which we are used to do in other languages such as Java or Scala.
  • Generally we define a function as:
fun fun_name(a: data_type, b: data_type, ......): return_type { // other codes return }
  • fun– Keyword to define a function.
  • fun_name – Name of the function which later used to call the function.
  • a: data_type – Here, a is an argument passed and data_type specify the data type of argument like integer or string.
  • : return_type – Specify the type of data value return by the function.
  • {….} – Curly braces represent the block of function.
 

⇒ Single Line Function:-

 
fun evenOrOdd(num1 : Int) = if(num % 2 == 0) "Even" else "Odd"
fun add(num1 : Int, num2 : Int) = num1 + num2
 

⇒ Default Arguments:-

  • Parameter with Defalut Argument.
fun printMessage(count: Int = 2){ for(i in 1..count){ println("Hello $i") } }

⇒ Unit Functions:-

  • In Kotlin ,By default return type is Unit.
  • If function has not define any return type Explicitly and also function not returning any value while calling.
  • Then , its default return type will be Unit.
fun evenOrOdd(num : Int) { val result = if(num % 2 == 0) "Even" else "Odd" println(result) }

Calling of user-defined function-

We create a function to assign a specific task. Whenever a function is called the program leaves the current section of code and begins to execute the function. 
The flow-control of a function-
  1. The program comes to the line containing a function call.
  1. When function is called, control transfers to that function.
  1. Executes all the instruction of function one by one.
  1. Control is transferred back only when the function reaches closing braces or there any return statement.
  1. Any data returned by the function is used in place of the function in the original line of code.
fun mul(a: Int, b: Int): Int { var number = a.times(b) return number } fun main(args: Array<String>) { var result = mul(3,5) println("The multiplication of two numbers is: $result") }
 

Advantages of using functions in Kotlin:

  1. Modularity: Functions provide a way to modularize your code and break it down into smaller, more manageable parts. This makes your code more readable, maintainable, and easier to test.
  1. Reusability: Functions can be called from multiple locations in your code, making it easy to reuse your code and avoid duplication.
  1. Improved Readability: Functions provide a way to encapsulate complex logic into reusable blocks of code, which can make your code more readable and easier to understand.
  1. Improved Abstraction: Functions can be used to abstract away complex logic, making it easier to understand what a piece of code does without having to examine its implementation details.

Disadvantages of using functions in Kotlin:

  1. Overhead: Functions can increase the size of your code and increase the amount of memory required to execute it, especially if you have many functions.
  1. Debugging: Functions can make debugging more difficult if you have complex logic inside your functions, especially if you have multiple functions that call each other