Function

Function is a set of code which may take some parameters, perform certain operations on them, and then may return a value.

Kotlin uses "fun" keyword to declare a function, and you can use traditional ways, like C, C++, and Java, to call them.

General Syntax

  1. <Access specifire> fun  
  2.     <Function name>(parametors) : returntype  
  3.     {   
  4.       //body statements. return  
  5.         <value>;   
  6.     }  
Example

Printing a message using function                                            
  1. fun main(args: Array < String > )  
  2. {  
  3.     println("Message=" + welcomeMessage())  
  4. }  
  5. fun welcomeMessage(): String {  
  6.     var msg: String = "Hello Android"  
  7.     return msg  
  8. }  
  9. // output: Message=Hello Android  

Passing Parameters

Function parameters are defined as name: type. Parameters are separated using comma. Each parameter must be explicitly typed.

  1. fun main(args: Array < String > )  
  2. {  
  3.     println("area of square=" + area(5))  
  4. }  
  5. fun area(x: Int): Int {  
  6.     return x * x  
  7. }  
  8. //output:  area of square=25  

Default Arguments

You can use the default value of parameter when the corresponding parameter is omitted.

  1. fun read(off: Int = 0, length: Int = b.size) { //body statements} 
  • Default values are defined using the =after type along with the value.
  • Overriding methods always use the same default parameter values as the base method.
Named Argument

You can name a list of parameters for making it readable and for convenience.

  1. fun sample(pwd: String, wordseparator: Char = ’_’, uppercase: Boolean = true, lowercse: Boolean = true, number: Boolean = true, specialchar: Boolean = true)  
  2. {   
  3.   // body statements…………………  
  4. }  

Now, you can call this function like this –

sample(pwd)

or  sample(pwd,true,true,true)

Unit Returning Type 

It is optional return type. Suppose, you do not want to return any value/data from Function. You can use Unit type.

Example

  1. fun main(args: Array < String > ) {  
  2.     showMessage();  
  3. }  
  4. fun showMessage(): Unit {  
  5.     println("Hello Android")  
  6. }  
  7. //output: Hello Android  

Lambda Function 

Syntax

  1. val functionName = {  
  2.     param_var: Type - > operation  
  3. }  
  4. or  
  5. val functionname: (param_Type) - > return_Type = {  
  6.     operation on param here  
  7. }  
  8. now you can use it as traditional  
  9. function call i.e.–  
  10. function_name(param)  

Example

Create a lambda function to calculate the area of a rectangle.

  1. val area =  
  2.   {  
  3.     width: Double,  
  4.     height: Double - > width * height  
  5. //lambda function to calculate area  
  6. fun main(args: Array < String > ) {  
  7.     println("Area of Rectangle=" + area(5.5, 5.5))  
  8. }  
  9. //output: Area of Rectangle=30.25   

Inline Function

When you use the inline keyword with function, it copies the body statement of the inline function at its invoking code which reduces the control jumping from calling statement to a definition of the function.

Example

Write a program to illustrate inline function.

  1. inline fun printMessage(message: () - > Unit) {  
  2.     println("Line before calling lambda function")  
  3.     message()  
  4.     println("Line after calling lambda function")  
  5. }  
  6. fun main(args: Array < String > ) {  
  7.     printMessage {  
  8.         println("Calling exact function")  
  9.     }  
  10. }  
  11. /* 
  12.  
  13. Output: 
  14.  
  15. Line before calling lambda function 
  16.  
  17. Calling exact function 
  18.  
  19. Line after calling lambda function 
  20.  
  21. */  

Use ctrl+shift+A to get the search dialog and search here for Kotlin bytecode. You can see the bytecode so now, decompile this bytecode which will be visible in Java.            

  1. public final class Example_inline_lambdaKt {  
  2.    public static final void printMessage(@NotNull Function0 message) {  
  3.       Intrinsics.checkParameterIsNotNull(message, "message");  
  4.       String var2 = "Line before calling lambda function";  
  5.       System.out.println(var2);  
  6.       message.invoke();  
  7.       var2 = "Line after calling lambda function";  
  8.       System.out.println(var2);  
  9.    }  
  10.   
  11.    public static final void main(@NotNull String[] args) {  
  12.       Intrinsics.checkParameterIsNotNull(args, "args");  
  13.       String var1 = "Line before calling lambda function";  
  14.       System.out.println(var1);  
  15.       String var2 = "Calling exact function";  
  16.       System.out.println(var2);  
  17.       var1 = "Line after calling lambda function";  
  18.       System.out.println(var1);  
  19.    }  
  20. }  

tailrec function [Recursive Function]

Recursive functions are those functions which call themselves several times within their body .You can use ’tailrec’ keyword before fun keyword in function definition. This keyword prevents the program from stack overflow.  Let us understand working of this keyword with an example-

Example

Write a program to find nth number of  Fibonacci series.

  1. import java.math.BigInteger  
  2. fun main(args: Array < String > ) {  
  3.     println("factorial =" + getfabinockyNum(10000, BigInteger("1"), BigInteger("1")))  
  4. }  
  5. tailrec fun getfabinockyNum(n: Int, a: BigInteger, b: BigInteger): BigInteger {  
  6.     if (n == 0) {  
  7.         return b  
  8.     } else {  
  9.         return getfabinockyNum(n - 1, a + b, a)  
  10.     }  
  11. //output: factorial .=54438373113565281338734260993750380135389184554695967…………768..23814710669912644214775254478587674568963808002962265133111359929762726679441400101575800043510777465935805362502461707918059226414679005690752321895868142367849593880756423483754386342639635970733756260098962462668746112041739819404875062443709868654315626847186195620146126642232711815040367018825205314845875817193533529827837800351902529239517836689467661917953884712441028463935449484614450778762529520961887597272889220768537396475869543159172434537193611263743926337313005896167248051737986306368115003088396749587102619524631352447499505204198305187168321623283859794627245919771454628218399695789223798912199431775469705216131081096559950638297261253848242007897109054754028438149611930465061866170122983288964352733750792786069444761853525144421077928045979904561298129423809156055033032338919609162236698759922782923191896688017718575555520994653320128446502371153715141749290913104897203455577507196645425232862022019506091483585223882711016708433051169942115775151255510251655931888164048344129557038825477521111577395780115868397072602565614824956460538700280331311861485399805397031555727529693399586079850381581446276433858828529535803424850845426446471681531001533180479567436396815653326152509571127480411928196022148849148284389124178520174507305538928717857923509417743383331506898239354421988805429332440371194867215543576548565499134519271098919802665184564927827827212957649240235507595558205647569365394873317659000206373126570643509709482649710038733517477713403319028105575667931789470024118803094604034362953471997461392274791549730356412633074230824051999996101549784667340458326852960388301120765629245998136251652347093963049734046445106365304163630823669242257761468288461791843224793434406079917883360676846711185597501  
  • Without using ‘tailrec’ keyword, this program will return ‘StackOverflow ’ exception.
High Order Functions

When a function has a function as a parameter, it is called high order function .To understand better with user defined function, see the example of Inline Function.

  1. fun main(args: Array < String > )  
  2. {  
  3.     var data = mutableListOf < Int > (1, 2, 3, 4, 5)  
  4.     data.forEach {  
  5.         println(it)  
  6.     }  
  7. }  
  8. //output :  
  9. 1  
  10. 2  
  11. 3  
  12. 4  
  13. 5  

Explanation

In this example, ‘forEach()’ has a method println() as a parameter. It takes a single element of the list one by one and put it in variable ‘it’ which will be printed using println() method. This is the abbreviated code of data.forEach{println(it)}.

  1. For(x in data)   
  2. {  
  3.     println(x)