Anonymous Functions and Lambdas – Kotlin

(Last Updated On: September 20, 2017)

Note! This is a post for beginners in Kotlin language.

What are lambdas and anonymous functions? In order to define them let’s see what is a function literal.

Function literal

Function literal is a function that was not declared, but was passed as an expression.

What functions are ‘function literal’?

The following are called ‘function literal’:

  • lambda expressions
  • anonymous functions

Lambda Expressions

Full syntax:

Pass lambda as a parameter to a function with more parameters

NOTE: The equivalent syntax for sum function is:

Let’s do some analysis on this function. It requires the first 2 parameters to be of type int, and the last one as a lambda expression. The lambda expression requires 2 parameters of type int (a, b) and returns an int.

So far, so good. The sum function must return an int also, so when we return lambda (c(a,b)) we actually return an int value in the end.

Also, as you can see, when we want to return a lambda we have to use parentheses with parameters, when they exist. When there is no parameter, then we write only empty parentheses.

Pass lambda to a function that has only the lambda function as parameter

Also the equivalent syntax for one function is:

Overview

  • lambdas are always surrounded by curly braces ‘{}’
  • parameters are defined before “->” symbol
  • the body (what your method should return) is defined after “->” symbol
  • if a function has:
  • more parameters and the last parameter of a function is a lambda expression, then the lambda expression can go outside the parentheses
  • only one parameter and the last parameter is a lambda expression, then we can write the lambda expression without parentheses
  • if we have only one parameter in a lambda expression, and we do not use it, we can omit itwhen a lambda has only one parameter and Kotlin can figure the signature out itself, we do not have to declare that parameter. Kotlin will declare it for us under the name “it”
  • return inside an lambda expression will return from the enclosing function

Anonymous functions

As a block:

As an expression:

Overview

  • Anonymous functions are like regular functions, but without a name
  • parameter types can be omitted if they can be inferred from context
  • parameters are always passed inside the parentheses. If the last parameter of a function is an anonymous function, the anonymous function cannot go outside the parentheses (this works only for lambdas)!
  • return inside an anonymous function will return from the anonymous function itself

You can learn more from https://kotlinlang.org/docs/reference/lambdas.html#lambda-expressions-and-anonymous-functions