DEV Community

Cover image for Basics of Kotlin - Part 4
Chetan
Chetan

Posted on

Basics of Kotlin - Part 4

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 Basics of Kotlin- Part 3. Let's learn more about Kotlin.

Functions:

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

  • Standard library function:

    Standard library function is built-in library functions that can be defined implicitly and available for use.
fun main(args: Array<String>){  
var number = 16
var result = Math.sqrt(number.toDouble())  
print("$result")  
}
Output : 4
Enter fullscreen mode Exit fullscreen mode

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.

  • User-Defined Functions:

    User-defined functions are created by the user and can be used for advanced programming. Here functions are declared by using fun keyword.
fun main(){
   functionName()
}
fun functionName(){
     //body of function
}
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

Here we create a function add 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.

Tail-recursion:

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 java.lang.StackOverflowError. To handle this Kotlin have tailrec function. When a function is marked with the tailrec 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:

The recursive call must be the last call of the method. 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
Enter fullscreen mode Exit fullscreen mode

Lambda Expressions:

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}
Enter fullscreen mode Exit fullscreen mode

Lambda expression syntax
The full syntactic form of lambda expressions is as follows:

val sum: (Int, Int) -> Int = { x: Int, y: Int -> x + y }
Enter fullscreen mode Exit fullscreen mode
  • A lambda expression is always surrounded by curly braces.
  • Parameter declarations in the full syntactic form go inside curly braces and have optional type annotations.
  • The body goes after an -> sign.
  • 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.
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
Enter fullscreen mode Exit fullscreen mode

Exception Handling in Kotlin:

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:

  • try: try block contains a block of statements which might create the exception. It is always followed by either catch or finally or both.
  • catch: It is used to catch an exception thrown from the try block.
  • finally: It is used to checks whether the exception is handled or not.
  • throw: It is used to throw an exception explicitly.
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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

That's it for this article. We will continue in the next article.

Happy Learning!

Top comments (0)