Saturday, 3 February 2018

Kotlin: Lambda Expressions

By using lambda expressions, you can define a function without function name.

You can define lambda expression using curly braces. The parameters are declared before -> and body is defined after ->

Syntax
{arg1, arg2...argN -> expression}

arg1 arg2…argN are the arguments passed to the function and expression represents the function body.

fun processData(arr: Array<Int>, functionToProcess: (Int) -> Int): IntArray {
         ...
         ...
}

For example, above function takes two arguments
a. array of integers, and
b. A function that takes an integer as argument and return an integer

You can call the above function in two ways.

1. By passing the function directly
fun doubleMe(x: Int) = 2 * x
var arr1 = Array(5, { i -> i })
doubleArrayElements = processData(arr1, ::doubleMe)

2. By using lambda expression
var arr1 = Array(5, { i -> i })
doubleArrayElements = processData(arr1, { x -> 2 * x })

Find the below working application.

FunctionDemo.kt

fun doubleMe(x: Int) = 2 * x

fun processData(arr: Array<Int>, functionToProcess: (Int) -> Int): IntArray {
 var result = IntArray(arr.size)

 var counter = 0

 for (ele in arr) {
  result[counter++] = functionToProcess.invoke(ele)
 }

 return result
}

fun printArray(arr: IntArray) {
 println("Elements in array are")
 for (ele in arr) {
  print("$ele ")
 }
 println()
}


fun main(args: Array<String>) {
 var arr1 = Array(5, { i -> i })

 /* Higher order function using lambda expression */
 var doubleArrayElements = processData(arr1, { x -> 2 * x })
 printArray(doubleArrayElements)

 doubleArrayElements = processData(arr1, ::doubleMe)
 printArray(doubleArrayElements)
}

Output

Elements in array are
0 2 4 6 8 
Elements in array are
0 2 4 6 8


Previous                                                 Next                                                 Home

Kotlin: Higher Order function

Higher order function
A function that takes other function as argument (or) returns a function as result (or) both is called higher order function.

fun processData(arr: Array<Int>, functionToProcess: (Int) -> Int): IntArray {
         ...
         ...
}

For example, above function takes two arguments
a.    array of integers, and
b.   a function that takes an integer as argument and return an integer

How to call above function?
By using function reference operator ::, you can pass a function as argument.

fun doubleMe(x: Int): Int = x * 2
processData(arr1, ::doubleMe)

Find the below working application.

FunctionDemo.kt

fun doubleMe(x: Int): Int = x * 2
fun squareMe(x: Int): Int = x * x

fun processData(arr: Array<Int>, functionToProcess: (Int) -> Int): IntArray {
 var result = IntArray(arr.size)

 var counter = 0

 for (ele in arr) {
  result[counter++] = functionToProcess.invoke(ele)
 }

 return result
}

fun printArray(arr: IntArray) {
 println("Elements in array are")
 for (ele in arr) {
  print("$ele ")
 }
 println()
}


fun main(args: Array<String>) {
 var arr1 = Array(5, { i -> i })

 var doubleArrayElements = processData(arr1, ::doubleMe)
 printArray(doubleArrayElements)

 var squareArrayElements = processData(arr1, ::squareMe)
 printArray(squareArrayElements)
}

Output

Elements in array are
0 2 4 6 8 
Elements in array are
0 1 4 9 16


Previous                                                 Next                                                 Home

Kotlin: Tail recursive functions

In this post, I am going to explain about the concept called tail recursion. This is a new concept, used to build recursive functions effectively in functional programming languages. Most of the people think that recursion is inefficient, but that is not true. The efficiency of recursion is depending on the way you code it.

Below snippet calculates the factorial of a number.

fun fact(n: Int): Int {
         if (n == 0) return 1
         return n * fact(n - 1)
}

Programming languages maintain stack frames to keep track of recursive calls. Following step-by-step procedure explains that.


Step 1: fact(5) = 5 * fact(5-1) = 5 * fact (4)
Step 2: fact(4) = 4 * fact(3), to get the result of fact(4), we need to calculate fact(3) first.
Step 3: fact(3) = 3 * fact(2), to get the result of fact(3), we need to calculate fact(2) first.
Step 4: fact(2) = 2 * fact(1), to get the result of fact(2), we need to calculate fact(1) first.
Step 5: fact(1) = 1 * fact(0), to get the result of fact(1), we need to calculate fact(0) first.
Finally, we reached our base condition, fact(0) = 1.
fact(1) = 1 * fact(0) =  1 * 1 = 1
fact(2) = 2 * fact(1) =  2 * 1 = 2
fact(3) = 3 * fact(2) =  3 * 2 = 6
fact(4) = 4 * fact(3) =  4 * 6 = 24
fact(5) = 5 * fact(4) =  5 * 24 = 120

To calculate fact(5), We require 5 stack frames, So to calculate fact(1000000), we require 1000000 stack frames. Since stack is limited in size, you will end up in stack overflow error for large values, and also it impacts performance for large values.

How tail recursion helps in this scenario?
When you define a function as tail recursive function, compiler optimizes the recursion.

How to define a tail recursive function?
By using tailrec modifier, you can define a tail recursive function. To make a function tail recursive, it should meet one precondition. The function must call itself as the last operation it performs.

We can rewrite the factorial function like below.

tailrec fun fact(n: Int, accum: Int = 1): Int{
         var soFar = n * accum
    return if (n <= 1) {
        soFar
    } else {
        fact(n - 1, soFar)
    }
}

When you ran above function, kotlin optimizes the recursive function and it replaces the stack frame with last result.

fact(5) = fact(4, 5*1)
                 = fact(3, 5*4)
                 = fact(2, 20*3)
                 = fact(1, 60*2)
                 = 120


Previous                                                 Next                                                 Home

Kotlin: Member functions

A function that is defined inside a class (or) object is called member function.

Ex
class Number {

         fun isEven(num: Int): Boolean {
                 return num % 2 == 0
         }
}

In above snippet, isEven is a member function.

FunctionDemo.kt

class Number {

 fun isEven(num: Int): Boolean {
  return num % 2 == 0
 }
}

fun main(args: Array<String>) {
 var obj = Number()

 var is5Even = obj.isEven(5)
 var is6Even = obj.isEven(6)

 println("Is 5 Even : $is5Even")
 println("Is 6 Even : $is6Even")
}

Output

Is 5 Even : false
Is 6 Even : true


Previous                                                 Next                                                 Home

Friday, 2 February 2018

Kotlin: Local functions

In kotlin, you can define a function inside other function.

Ex
fun factorial(n: Int): Int {
         fun fact(n: Int): Int {
                 if (n == 0) return 1
                 return n * fact(n - 1)
         }

         if (n < 0) return -1
         else return fact(n)
}

As you see above snippet, I defined fact inside the factorial function. ‘fact’ is the local function, whereas factorial is the outer function.

FunctionDemo.kt
fun factorial(n: Int): Int {
 fun fact(n: Int): Int {
  if (n == 0) return 1
  return n * fact(n - 1)
 }

 if (n < 0) return -1
 else return fact(n)
}

fun main(args: Array<String>) {

 var factorialOf5 = factorial(5)

 println("factorial Of 5 : $factorialOf5")
}

Output
factorial Of 5 : 120


Local functions can access the data defined in outer functions.

Previous                                                 Next                                                 Home

Kotlin: infix functions

In kotlin, you can call functions in infix notation.  Infix functions are defined using the keyword ‘infix’. Infix functions must have a single parameter.

You can make a function as infix function, if the function
a.   Is a member function (or) extension function
b.   Has only single parameter
c.   Is marked with keyword infix

Infix member function
class EvenNumber {

 infix fun isEven(num: Int): Boolean {
  if (num % 2 == 0) return true
  return false
 }

}

As you see isEven is defined as infix function using the keyword infix.

How to call isEven function?
var is5Even = obj isEven 5    // Same can be called obj.isEven(5)


InfixDemo.kt
class EvenNumber {

 infix fun isEven(num: Int): Boolean {
  if (num % 2 == 0) return true
  return false
 }

}

fun main(args: Array<String>) {
 var obj = EvenNumber()

 var is5Even = obj isEven 5    // Same can be called obj.isEven(5)
 var is6Even = obj isEven 6    // Same can be called obj.isEven(5)

 println("Is 5 even number $is5Even")
 println("Is 6 even number $is6Even")
}

Output
Is 5 even number false
Is 6 even number true


Infix extension funcitons
In kotlin, you can extend the functionality of a class, by using extension functions.


For example, below code add doubleEven function to the class EvenNumber.
infix fun EvenNumber.doubleEven(num: Int): Int {

 if (isEven(num)) {
  return num * 2
 }
 return -1
}


InfixDemo.kt
class EvenNumber {

 infix fun isEven(num: Int): Boolean {
  if (num % 2 == 0) return true
  return false
 }

}

infix fun EvenNumber.doubleEven(num: Int): Int {

 if (isEven(num)) {
  return num * 2
 }
 return -1
}

fun main(args: Array<String>) {

 var obj = EvenNumber()

 var double6 = obj doubleEven 6   // Same can be called obj.doubleEven(5)

 println("Double 6 $double6")
}


Output
Double 6 12






Previous                                                 Next                                                 Home

Thursday, 1 February 2018

Kotlin: Single Expression functions

When a function returns single expression, you can omit curly braces.

Ex
fun square(num: Int) = num * num
fun cube(num: Int) = num * num * num

FunctionDemo.kt
fun square(num: Int) = num * num
fun cube(num: Int) = num * num * num

fun main(args: Array<String>) {
 println("Square of 5 is ${square(5)}")
 println("Cube of 5 is ${cube(5)}")
}

Output
Square of 5 is 25
Cube of 5 is 125



Previous                                                 Next                                                 Home