Kotlin Function

Function is used for combine similar type of operation and single or multiple statement. Almost all modern programming language are supported to this features. There are also called method, subroutine in other programming. The advantage of function is , that is are define one time. And possible to execute many time during program executions. This process is provide reusability of codes. In this post are mentioned basic concepts of how to define and use kotlin user defined functions.

Define kotlin functions

Normal function of kotlin is start with keyword "fun". after of this keyword will mention that specified the name of function. After that within the parenthesis given list of arguments (parameters) of this function. This is optional when function are not accept any value.

outside of parentheses are mention of function return type value. Most of cases function are not return any value. In this case there is no return type. There syntax as follows.

fun functionName(variable:dataType, variable:dataType ): returnType{
//body of this function
}

For example.

/*
 * keyword : fun  
 * function Name : info 
 * @Accepted two integer parameter value 
 * @returned one integer value
 * */
fun info(data1: Int, data2: Int): Int{
    //define logic and statement here
    //return Int result
}

When we define function in kotlin program and compile the program. Kotlin compiler is understand following things. How many parameter is accept by function, data type of parameters, default values of paramters and return value by function. Normally function is divided into 4 section. There as follows.

Function no argument and no return value

That is basic function that are not accepted any function parameter and not return any value. For example.

fun message(){
   //not accepted any parameter and not return any value
    print("This is an simple message function")
}
fun main(args: Array<String>){
    //call function
   message()
}

Output

This is an simple message function

When function are not returning any value so we can also use Unit type. See this example.

fun message():Unit{
    print("message function")
}
fun main(args: Array<String>){
    //call function
    message()
}

Function Accept argument and no return value

fun add(a:Int,b:Int,c:Int){
    print(" Sum of ($a + $b + $c) = ${a+b+c}")
}
fun main(args: Array<String>){
    //call function
    add(1,2,3)
}

Output

Sum of (1 + 2 + 3) = 6

Function Accept argument and return value

There are some cases function are accept argument value and return some value. For example.

fun add(a:Int,b:Int,c:Int):Int{
   return a+b+c
}
fun main(args: Array<String>){
    //call function
    print(add(1,2,3))
}

Output

6

Function No argument, and return value

some of situation we are need to write a function definition which is not accepted any value that means no function arguments. But this function are return some result. for example

fun code():String{
    return "Welcome to kotlin code"
}
fun main(args: Array<String>){
    //call function
    print(code())
}

Output

Welcome to kotlin code

Set default parameter to kotlin function

default value of function parameters are used to work with multiple situations. That means default parameter value are set by program that value is not always compulsory. When provide the value of default argument in function calling execution so this will be replace new upcoming value on default value.

/*
*   function :add
*   parm: three integer values
*   default: y and z is = 0
*   @return:sum of integers
*/
fun add(x:Int,y:Int=0,z:Int=0):Int{
   return x+y+z;
}
fun main(args: Array<String>) {
    
   println(add(1,2)) //work of two integers
   println(add(1,2,3)) //working on 3 integers

}

Output

3
6

Note that set default value from right to left in function parameters.

Kotlin Inline functions

inline function is special function that can be defined of any place within the program. That are define by of inside the function and outside the function. For example

//inline golbal function
var addition={x:Int,y:Int ->x+y}
fun main(args: Array<String>) {
   val data1:Int =2
   val data2:Int =4
   println("addition : ${addition(data1,data2)}")
   //inline local function
   var subtract={x:Int,y:Int ->x-y}
   println("subtract : ${subtract(data1,data2)}")
}

Output

addition : 6
subtract : -2

Function Named Arguments

Naming argument is special concept to reordering function parameter value at anytime. This process can be provide more readable codes.


//Function to display information
fun info(name:String,address:String){

  println("name   : $name")
  println("address: $address\n")
}

fun main(args: Array<String>) {
   
   // Foo value is assign to name field
   // Anywhere value is assign to address field
   info("Foo","Anywhare") 

   //Named Argument to set value 
   info(address="Everywhere",name="God")
}

Output

name   : Foo
address: Anywhare

name   : God
address: Everywhere

But note that there is not possible to provide both simple value and naming argument at same time. See this example.


//Function to display information
fun info(name:String,address:String){

  println("name   : $name")
  println("address: $address\n")
}

fun main(args: Array<String>) {
   
   // Foo value is assign to name field
   // Anywhere value is assign to address field
   info("Foo","Anywhare") 

   //Named Aragumet to set value 
   info(address="Everywhere","God")
}

Output

kotlin.kt:16:30: error: mixing named and positioned arguments is not allowed
   info(address="Everywhere","God")
                             ^
kotlin.kt:16:35: error: no value passed for parameter 'name'
   info(address="Everywhere","God")

Variable Number of Arguments

That is special function that are capable to get multiple undefined number of parameters. That is defined by vararg variable and that are stored similar type of elements. When we pass multiple element of this function that are create an array internally and we are capable to used to that elements.

//define variable length arguments
fun sum(vararg items:Int):Long{
  println("Passed Elements : ${items.size}")  
  var result:Long=0
  for (i in items){
    result+=i;
  }
  return result;
}

fun main(args: Array<String>) {
   
   println(sum(1,2));
   println(sum(1,2,3));
   println(sum(10,5,3,2));
}

Output

Passed Elements : 2
3
Passed Elements : 3
6
Passed Elements : 4
20

Function References

fun checkEven(x: Int)  = ( x % 2 == 0)
fun main(args: Array<String>){
   //pass checkEven reference to map
  print(listOf(1,8,2,7,30).map(::checkEven))
}

Output

[false, true, true, false, true]

Lambda Expression

fun main(args: Array) 
{ 
    val testing = {print("① go 2 rest\n");}
    // invoke anonymous function
    testing.invoke() 
    testing() 
} 

Output

① go 2 rest
① go 2 rest


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved