Saturday, 3 February 2018

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

No comments:

Post a Comment