Kotlin functions - GeeksforGeeks

28 Mar, 2022
A 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. For example: If we have to compute sum of two numbers then define a fun sum().
fun sum(a: Int, b: Int): Int {
    return a + b
}
We can call sum(x, y) at any number of times and it will return sum of two numbers. So, function avoids the repetition of code and makes the code more reusable. In Kotlin, there are two types of function- 
Standard library function
User defined 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. 
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.
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.
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.
  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
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-
The program comes to the line containing a function call.When function is called, control transfers to that function.Executes all the instruction of function one by one.Control is transferred back only when the function reaches closing braces or there any return statement.Any data returned by the function is used in place of the function in the original line of code.
The program comes to the line containing a function call.
When function is called, control transfers to that function.
Executes all the instruction of function one by one.
Control is transferred back only when the function reaches closing braces or there any return statement.
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: 30
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.
ayushpandey3july
Kotlin Functions
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Android RecyclerView in Kotlin
Retrofit with Kotlin Coroutine in Android
Kotlin Android Tutorial
Kotlin when expression
How to Get Current Location in Android?
Android Menus
ImageView in Android with Example
Kotlin constructor
Android SQLite Database in Kotlin
MVP (Model View Presenter) Architecture Pattern in Android with Example