Kotlin - Functions

Kotlin is a statically typed language, hence, functions play a great role in it. We are pretty familiar with function, as we are using function throughout our examples in our last chapters. A function is a block of code which is written to perform a particular task. Functions are supported by all the modern programming languages and they are also known as methods or subroutines.
At a broad level, a function takes some input which is called parameters, perform certain actions on these inputs and finally returns a value.
Kotlin provides a number of built-in functions, we have used a number of buil-in functions in our examples. For example print() and println() are the most commonly used  built-in function which we use to print an output to the screen.
fun main(args: Array<String>) {
   println("Hello, World!")
}

Kotlin allows us to create our own function using the keyword fun. A user defined function takes one or more parameters, perform an action and return the result of that action as a value.
fun functionName(){  
   // body of function 
}  

Once we defined a function, we can call it any number of times whenever it is needed. Following isa simple syntax to call a Kotlin function:
functionName()

Following is an example to define and call a user-defined function which will print simple "Hello, World!":
fun main(args: Array<String>) {

   printHello()
   
}

fun printHello(){
   println("Hello, World!")
}

When you run the above Kotlin program, it will generate the following output:
Hello, World!

A user-defined function can take zero or more parameters. Parameters are options and can be used based on requirement. For example, our above defined function did not make use of any paramenter.
Following is an example to write a user-defined function which will add two given numbers and print their sum:
fun main(args: Array<String>) {
   val a = 10
   val b = 20
   
   printSum(a, b)
   
}

fun printSum(a:Int, b:Int){

   println(a + b)
}

When you run the above Kotlin program, it will generate the following output:
30

A kotlin function return a value based on requirement. Again it is very much optional to return a value.
To return a value, use the return keyword, and specify the return type after the function's parantheses
Following is an example to write a user-defined function which will add two given numbers and return the sum:
fun main(args: Array<String>) {
   val a = 10
   val b = 20
   
   val result = sumTwo(a, b)
   println( result )
   
}

fun sumTwo(a:Int, b:Int):Int{
   val x = a + b
   
   return x
}

When you run the above Kotlin program, it will generate the following output:
30

If a function does not return a useful value, its return type is Unit. Unit is a type with only one value which is Unit.
fun sumTwo(a:Int, b:Int):Unit{
   val x = a + b
   
   println( x )
}

The Unit return type declaration is also optional. The above code is equivalent to:
fun sumTwo(a:Int, b:Int){
   val x = a + b
   
   println( x )
}

Recursion functions are useful in many scenerios like calculating factorial of a number or generating fibonacci series. Kotlin supports recursion which means a Kotlin function can call itself.
fun functionName(){  
   ...
   functionName()
   ...
}  

Following is a Kotlin program to calculate the factorial of number 10:
fun main(args: Array<String>) {
   val a = 4
   
   val result = factorial(a)
   println( result )
   
}

fun factorial(a:Int):Int{
   val result:Int
   
   if( a <= 1){
      result = a
   }else{
      result = a*factorial(a-1)
   }
   
   return result
}

When you run the above Kotlin program, it will generate the following output:
24

A recursive function is eligible for tail recursion if the function call to itself is the last operation it performs.
Following is a Kotlin program to calculate the factorial of number 10 using tail recursion. Here we need to ensure that the multiplication is done before the recursive call, not after.
fun main(args: Array<String>) {
   val a = 4
   
   val result = factorial(a)
   println( result )
   
}

fun factorial(a: Int, accum: Int = 1): Int {
    val result = a * accum
    return if (a <= 1) {
        result
    } else {
        factorial(a - 1, result)
    }
}


When you run the above Kotlin program, it will generate the following output:
24

A higher-order function is a function that takes another function as parameter and/or returns a function.
Following is a function which takes two integer parameters, a and b and additionally, it takes another function operation as a parameter:
fun main(args: Array<String>) {
   
   val result = calculate(4, 5, ::sum) 
   println( result )
   
}
fun sum(a: Int, b: Int) = a + b 

fun calculate(a: Int, b: Int, operation:(Int, Int) -> Int): Int {
    return operation(a, b)                                       
}

When you run the above Kotlin program, it will generate the following output:
9

Here we are calling  the higher-order function passing in two integer values and the function argument ::sum. Here :: is the notation that references a function by name in Kotlin.
Let's look one more example where a function returns another function. Here we defined a higher-order function that returns a function. Here (Int) -> Int represents the parameters and return type of the square function.
fun main(args: Array<String>) { 
   val func = operation() 
   println( func(4) )
   
}
fun square(x: Int) = x * x

fun operation(): (Int) -> Int {
    return ::square                                       
}

When you run the above Kotlin program, it will generate the following output:
9

Kotlin lambda is a function which has no name and defined with a curly braces {} which takes zero or more parameters and body of function.
The body of function is written after variable (if any) followed by -> operator.
{variable with type -> body of the function}  

fun main(args: Array<String>) { 

   val upperCase = { str: String -> str.toUpperCase() }  

   println( upperCase("hello, world!") )
   
}                           

When you run the above Kotlin program, it will generate the following output:
HELLO, WORLD!

An inline function is declared with inline keyword. The use of inline function enhances the performance of higher order function. The inline function tells the compiler to copy parameters and functions to the call site.
fun main(args: Array<String>) { 

   myFunction({println("Inline function parameter")})
   
}
inline fun myFunction(function:()-> Unit){
   println("I am inline function - A")

   function()
   
   println("I am inline function - B")
}                               

When you run the above Kotlin program, it will generate the following output:
I am inline function - A
Inline function parameter
I am inline function - B

Q 1 - Which of the following is true about Kotlin functions?
A - Kotlin functions can take one or more parameters
B - Kotlin functions can be recursive
C - Kotlin functions can return values.
D - All of the above
All the given statements are true about Kotlin functions
Q 2 - What will be the output of the following program:
fun main(args: Array<String>) {
   val a = 100000
   
   val result = factorial(a)
   println( result )
   
}

fun factorial(a:Int):Int{
   val result:Int
   
   if( a <= 1){
      result = a
   }else{
      result = a*factorial(a-1)
   }
   
   return result
}

A - This will print 0
B - This will raise just a warning
C - Compilation will stop with error
D - None of the above
This will stop with java.lang.StackOverflowError because compiler is unable to call large number of recursive function call.
Q 2 - What is Tail Recursion?
A - Calculations are performed first, then recursive calls are executed.
B - Tail Recursion avoids the risk of stack overflow
C - Recursive call passes the result of current step to the next recursive call
D - All of the above
All the statements A, B and C are correct about Trail Recursion.

    68 Lectures 
     4.5 hours 

 Arnab Chakraborty

    71 Lectures 
     5.5 hours 

 Frahaan Hussain

    18 Lectures 
     1.5 hours 

 Mahmoud Ramadan

    49 Lectures 
     6 hours 

 Catalin Stefan

    49 Lectures 
     2.5 hours 

 Skillbakerystudios

    22 Lectures 
     1 hours 

 CLEMENT OCHIENG
 Print
 Add Notes
 Bookmark this page