Saturday 3 February 2018

Kotlin: Anonymous functions

In my previous post, I explained about lambda expressions, one disadvantage of lambda expression is, you can’t specify the return type. Anonymous functions are similar to lambda expressions, where you can specify return type.

Ex
fun(x: Int): Int = 2 * x

As you see above snippet, it is anonymous function, which doubles the value. The syntax of anonymous function is just like a function, except it do not have function name.

You can also specify body of the anonymous function in curly braces like below.

fun(x: Int): Int {return 2 * x}

A 'return' expression required in a anonymous function with a block body ('{...}')

Find the below working application.

FunctionDemo.kt
fun processData(arr: IntArray, 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) {
 for (ele in arr) {
  print("$ele ")
 }
 println()
}

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

 println("Elements in arr1 are")
 printArray(arr1)

 /* Higher order function using anonymous function */
 var doubleArrayElements = processData(arr1, fun(x: Int): Int { return 2 * x })

 println("Elements in doubleArrayElements are")
 printArray(doubleArrayElements)

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

 println("Elements in doubleArrayElements are")
 printArray(doubleArrayElements)
}

Output

Elements in arr1 are
0 1 2 3 4 
Elements in doubleArrayElements are
0 2 4 6 8 
Elements in doubleArrayElements are
0 2 4 6 8

You can omit the parameter types, if they can be inferred from context.

Ex
fun(x): Int { return 2 * x }

You can also omit the return type for the anonymous function in non-block notation.

Ex
fun(x)= 2 * x



Previous                                                 Next                                                 Home

No comments:

Post a Comment