Open In App

Kotlin functions

Last Updated : 05 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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. 

What is Functions?

A function is a unit of code that performs a special task. In programming, the function is used to break the code into smaller modules which makes the program more manageable.

We can call sum(x, y) at any number of times and it will return the sum of two numbers. So, the function avoids the repetition of code and makes the code more reusable.

Parts_of_function

Note: There is a space between closing bracket ‘)’ and opening ‘{‘ .

Example of a Function

For example: If we have to compute the sum of two numbers then define a fun sum().

fun sum(a: Int, b: Int): Int {
Int c = a + b
return c
}

Parameters in Function

Function parameters are the defined as the elements that are passed to the function for further processing where operations are performed.

In above example, there are two parameters passed mentioned:

  • a of Integer type
  • b of Integer type

Body of Function

Here in the body we perform the operations to be performed in the function like in the above Example:

val c = a + b

Return Value

Return value is the value which is returned after the operation is performed in the function. In above example c is the value which is returned.

Types of Functions in Kotlin

In Kotlin, there are two types of functions:

  • User-defined function
  • Standard library function

1. Kotlin User-Defined Function

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

-> Creating User-Defined Function

In Kotlin, the function can be declared at the top, and no need to create a class to hold a function, which we are used to doing 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.

  Kotlin function mul() to Multiply two Numbers having same type of Parameters:

Kotlin
fun mul(num1: Int, num2: Int): Int {
    var number = num1.times(num2)
    return number
}


Explanation: We have defined a function above starting with fun keyword whose return type is an Integer.

>> mul() is the name of the function
>> num1 and num2 are names of the parameters being accepted by the function
  and both are Integer type.

 Kotlin function student() having different types of parameters:

Kotlin
fun student(name: String , roll_no: Int , grade: Char) {
    println("Name of the student is : $name")
    println("Roll no of the student is: $roll_no")
    println("Grade of the student is: $grade")
}


Explanation: We have defined a function using fun keyword whose return type in Unit by default.

>> student is the name of the function.
>> name is the parameter of String data type.
>> roll_no is the parameter of Integer data type
>> grade is the parameter of Character data type

-> 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.
  2. When function is called, control transfers to that function.
  3. Executes all the instruction of function one by one.
  4. Control is transferred back only when the function reaches closing braces or there any return statement.
  5. Any data returned by the function is used in place of the function in the original line of code.

Kotlin program to call the mul() function by passing two arguments: 

Kotlin
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")
}

Output:

The multiplication of two numbers is: 15 

Explanation: In the above program, we are calling the mul(3, 5) function by passing two arguments. When the function is called the control transfers to the mul() and starts execution of the statements in the block. Using in-built times() it calculates the multiple of two numbers and store in a variable number. Then it exits the function with returning the integer value and controls transfer back to the main() where it calls mul(). Then we store the value returned by the function into mutable variable result and println() prints it to the standard output.

Kotlin program to call the student() function by passing all arguments:

Kotlin
fun student( name: String , grade: Char , roll_no: Int) {
    println("Name of the student is : $name")
    println("Grade of the student is: $grade")
    println("Roll no of the student is: $roll_no")

}
fun main(args: Array<String>) {
    val name = "Praveen"
    val rollno = 25
    val grade = 'A'
    student(name,grade,rollno)
    student("Gaurav",'B',30)
}

Output:

Name of the student is : Praveen
Grade of the student is: A
Roll no of the student is: 25
Name of the student is : Gaurav
Grade of the student is: B
Roll no of the student is: 30n

Explanation: In the above program, we are calling the student() function by passing the arguments in the same order as required. If we try to jumble the arguments then it gives the type mismatch error. In the first call, we pass the argument using variables and in the second call, we pass the arguments values without storing in variables. So, both methods are correct to call a function.

2. Kotlin Standard Library Function

In Kotlin, there are different numbers of built-in functions already defined in the standard library and available for use. We can call them by passing arguments according to requirements. In the below program, we will use built-in functions arrayOf(), sum() and println(). The function arrayOf() requires 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. 

Below is the implementation of the standard library function:

Kotlin
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. 

Kotlin
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:

The 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.

Advantages and Disadvantages in Kotlin Function

-> 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.
  2. Reusability: Functions can be called from multiple locations in your code, making it easy to reuse your code and avoid duplication.
  3. 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.
  4. 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.
  2. 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.

To Know more about Kotlin refer to Kotlin Tutorial



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads