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

No comments:

Post a Comment