Kotlin syntax

To understand lambdas, consider functions as a datatype

Now just like variables can be passed and returned by functions, functions can also be passed/returned as arguments/by functions.

Let’s Understand how :, ->, (), {} are being used in kotlin,

val doNothing : (Int) -> Int = { value -> value }

: essentially means - is a

-> is used to pass the values and returning the expressions. Whatever value is on the left side of -> (=> in Javascript) is passed to the right side into the expression.

() is used to accept parameters

{} is used to execute expressions inside it.

Keep these things in mind and understanding lambdas become real easy.

Now Let’s Read the above function

Above is a(:) function(being assigned to a variable called doNothing) that takes (Int) as input and returns an Int. The logic to return the Int is written inside the expression.

FUNCTION NAME : INPUT PARAMS -> RETURN TYPE = EXPRESSION.

This is The God formula to understand lambdas. This will again come in handy when we will pass functions as arguments.

Every expression is a function, because essentially every expression is doing some task, in other words, some function.

Therefore we can say -> lambdas are Anonymous functions or expressions.

val add : (Int, Int) -> Int = { a, b -> a + b }

Now it’s easier to read above function.

Call it like

val result = add(2,3)

Let’s check what are higher order functions - functions that accept functions as arguments or return functions.

fun passMeFunction(abc: () -> Unit) {
  // I can take function
  // do something here
  // execute the function
  abc()
}

Here abc is the parameter name, () -> Unit is a function. Since abc is being called inside the function, it’s also called as callback function (The concept of callback functions and higher order functions is same in both the languages).

Decode it.

abc : meaning abc is a. () -> Unit meaning function that takes 0 arguments and returns Unit.

Let’s call this function.

First way

passMeFunction(
        {
          val user = User()
          user.name = "ABC"
          println("Lambda is awesome")
        }
)

So now while calling this function, we are passing an expression(a function itself).

Second way (Same as above)

passMeFunction(
fun abc(){
           val user = User()
           user.name = "ABC"
           println("Lambda is awesome")
         }
)

However since kotlin is concise, Third way (Again same as above)

passMeFunction {
  val user = User()
  user.name = "ABC"
  println("Lambda is awesome")
}

Understanding how we omitted () all together becomes important. So go ahead with first or second approach initially.

A normal function syntax in kotlin is:

fun returnMeAddFunction(<Arguments> : <Argument''s DataType>): <ReturnType> {
   // can do something and return function as well
   // returning function
   return <Return expression>
}

Now let’s return a function from inside a function

fun returnMeAddFunction(): ((Int, Int) -> Int) {
   // can do something and return function as well
   // returning function
   return ::add
}

Let’s understand how things work in javascript now.

-> in kotlin is same as => in javascript

let addTwoNumbers = (a, b) => {
  return a + b;  
};

FUNCTION NAME = INPUT PARAMS => EXPRESSION

Compare it with what we read in kotlin

val add : (Int, Int) -> Int = { a, b -> a + b }

FUNCTION NAME : INPUT PARAMS -> RETURN TYPE = EXPRESSION

let f = plusFive;
// f is assigned the value of plusFive

plusFive(3); // 8
// Since f has a function value, it can be invoked. 
f(9); // 14
const isEven = (n) => {
  return n % 2 == 0;
}
 
let printMsg = (evenFunc, num) => {
  const isNumEven = evenFunc(num);
  console.log(`The number ${num} is an even number: ${isNumEven}.`)
}
 
// Pass in isEven as the callback function
printMsg(isEven, 4); 
// Prints: The number 4 is an even number: True.

Look how forEach iterator takes a lambda

const numbers = [28, 77, 45, 99, 27];
 
numbers.forEach(number => {  
  console.log(number);
}); 

Array Method .map()

The .map() method executes a callback function on each element in an array. It returns a new array made up of the return values from the callback function.

The original array does not get altered, and the returned array may contain different elements than the original array.

const finalParticipants = ['Taylor', 'Donald', 'Don', 'Natasha', 'Bobby'];
 
const announcements = finalParticipants.map(member => {
  return member + ' joined the contest.';
})
 
console.log(announcements);

Array Method .filter() The .filter() method executes a callback function on each element in an array. The callback function for each of the elements must return either true or false. The returned array is a new array with any elements for which the callback function returns true.

Here, the array filteredArray will contain all the elements of randomNumbers but 4.

const randomNumbers = [4, 11, 42, 14, 39];
const filteredArray = randomNumbers.filter(n => {  
  return n > 5;
});

Array Method .reduce() The .reduce() method iterates through an array and returns a single value.

It takes a callback function with two parameters (accumulator, currentValue) as arguments. On each iteration, accumulator is the value returned by the last iteration, and the currentValue is the current element. Optionally, a second argument can be passed which acts as the initial value of the accumulator.

Here, the .reduce() method will sum all the elements of the array.

const arrayOfNumbers = [1, 2, 3, 4];
 
const sum = arrayOfNumbers.reduce((accumulator, currentValue) => {  
  return accumulator + currentValue;
});
 
console.log(sum); // 10


Thanks for reading!