Basics of Kotlin - Part 4
Tags: android, kotlin, programming, computerscience
Published: 2021-04-26 08:44:53

In the last article, we learnt about some basic concepts of Kotlin like conditional statements, loops and jump statements. Before reading this article make sure you had read the last article <a href="https://dev.to/csj5483/basics-of-kotlin-part-3-1nia">Basics of Kotlin- Part 3</a>. Let's learn more about Kotlin.

<h3>Functions:</h3>
Functions in any programming language is a group of an interrelated block of code that performs a specific task. Functions allow us to break a program into various small sub-module. Functions increase the readability of code, reusability of code, and makes a program easy to manage.

In Kotlin <b>fun</b> keyword is used to declare the function. There are two types of functions in Kotlin depending on whether it is available in the standard library or defined by the user.

<ul><li><h4>Standard library function:</h4> Standard library function is built-in library functions that can be defined implicitly and available for use.</li></ul>
```
fun main(args: Array<String>){  
var number = 16
var result = Math.sqrt(number.toDouble())  
print("$result")  
}
Output : 4
```
In the above code snippet :
**sqrt()** is a function defined in the library which returns the square root of a number.
**print()** function prints message to a standard output stream.

<ul><li><h4>User-Defined Functions:</h4> User-defined functions are created by the user and can be used for advanced programming. Here functions are declared by using <b>fun</b> keyword.</li></ul>
```
fun main(){
   functionName()
}
fun functionName(){
     //body of function
}
```
Here, we call the function into the main function to run codes inside the body functionName().
```
Template for function in Kotlin:
fun functionName(argument name:argument type):return type{
      //body of function
}
```
Below is an example of a user-defined function
```
fun main() {
  val x=6
  val y=8
  println("Sum of $x and $y is "+add(x,y))
}
fun add(x:Int, y:Int):Int{
    return x+y
}
```
Here we create a function <b>add</b> which is taking two arguments of int type and return type of this function is also int. We had called this function inside our main function.

<h3>Tail-recursion:</h3>
Kotlin supports a style of functional programming known as tail recursion. When we try to do a large number of recursive function call, we get an error <b>java.lang.StackOverflowError</b>. To handle this Kotlin have tailrec function. When a function is marked with the <b>tailrec</b> modifier and meets the required form, the compiler optimizes out the recursion, leaving behind a fast and efficient loop based version instead. Tail recursion follows one rule for implementation. This rule is as follow:

<b>The recursive call must be the last call of the method</b>. To declare a recursion as tail recursion we need to use tailrec modifier before the recursive function.

For example, to calculate the factorial of any number we can use the below method:
```
fun main(args: Array<String>) {  
    val number = 10  
    val result: Long  
    result = factorial(number)  
    println("Factorial of $number = $result")  
}  
  
tailrec fun factorial(n: Int, run: Int = 1): Long {  
    return if (n == 1){  
        run.toLong()  
    } else {  
        factorial(n-1, run*n)  
    }  
}
Output : 
Factorial of 10 = 3628800
```

<h4>Lambda Expressions:</h4>
Lambda is a function that has no name. Lambda is defined with curly braces {} which takes variable as a parameter (if any) and body of the function. The body of the function is written after the variable (if any) followed by the -> operator.
```
Syntax of lambda expression:
{ variable -> body_of_function}
```
<b>Lambda expression syntax</b>
The full syntactic form of lambda expressions is as follows:
```
val sum: (Int, Int) -> Int = { x: Int, y: Int -> x + y }
```
<ul><li>A lambda expression is always surrounded by curly braces.</li>
<li>Parameter declarations in the full syntactic form go inside curly braces and have optional type annotations.</li>
<li>The body goes after an -> sign.</li>
<li>If the inferred return type of the lambda is not Unit, the last (or possibly single) expression inside the lambda body is treated as the return value.</li>
</ul>
```
Program for adding two numbers using lambda
fun main(args: Array<String>) {  
    println(sum(5,6))
}  
val sum = { x: Int, y: Int -> x + y }
Output : 11
```


<h3>Exception Handling in Kotlin:</h3>
Exception in programming is defined as a run time problem that occurs in a program and leads to the termination of the program. Exceptions can occur due to less memory space, array out of bound, conditions like division by zero. To solve this type of error in the program exception handling is used.

Exception handling is defined as a process which handles the runtime problems and also maintains the flow of the program during execution.

In Kotlin all exception classes are descendants of class Throwable. Kotlin uses the 'throw' expression to throw an exception object.

There are four types of keywords used in exception handling. These are:
<ul><li><b>try:</b> try block contains a block of statements which might create the exception. It is always followed by either catch or finally or both.</li>
<li><b>catch:</b> It is used to catch an exception thrown from the try block.</li>
<li><b>finally:</b> It is used to checks whether the exception is handled or not.</li>
<li><b>throw:</b> It is used to throw an exception explicitly.</li></ul>

```
Example of try-catch
fun main (args: Array<String>){  
    try {   
        val res =  9/ 0  
        
    } catch (e: ArithmeticException) {  
        println(e)  
    }
}
Output :
java.lang.ArithmeticException: / by zero
```
We can throw an exception explicitly by using the throw keyword.
```
Example of try-catch using throw keyword
fun main (args: Array<String>){  
    try {   
       println("Inside throw")
       throw Exception("Exception throwed")
} catch (e: Exception) {  
        println(e)  
    }
}
Output:
Inside throw 
java.lang.Exception: Exception throwed
```
That's it for this article. We will continue in the next article.

Happy Learning!