Anonymous Functions and Lambdas – Kotlin

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.

val sum = { a: Int, b: Int -> a + b }

What functions are ‘function literal’?

The following are called ‘function literal’:

  • lambda expressions
  • anonymous functions

Lambda Expressions

Full syntax:

val sum = { a: Int, b: Int -> a + b }
Pass lambda as a parameter to a function with more parameters
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val s = sum(2,3, {a,b -> a+b})
    }


      private fun sum(a: Int, b: Int, c: (Int, Int) -> Int): Int {
       return c(a,b)  //returns a lambda which returns an int
   }
}

NOTE: The equivalent syntax for sum function is:

 private fun sum(a: Int, b: Int, c: (Int, Int) -> Int) = c(a,b)

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
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val p = one({2+3})
    }

    private fun one(c: () -> Int): Int {
      return c() //returns a lambda which returns an int but without parameters
    }
}

Also the equivalent syntax for one function is:

private fun one(c: () -> Int) = c()

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
    val s = sum(2,3) {a,b -> a+b}
  • only one parameter and the last parameter is a lambda expression, then we can write the lambda expression without parentheses
     val p = one{2+3}
  • 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”
    class MainActivity : AppCompatActivity() {
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
            val s = sum(2, {it * 3}) // returns s = 6, it = 2
        }
    
        private fun sum(a:Int, c: (Int) -> Int) :Int {
            return c(a)
        }
    }
  • return inside an lambda expression will return from the enclosing function

Anonymous functions

As a block:

fun(x: Int, y: Int): Int {
    return x + y
}

As an expression:

fun(x: Int, y: Int): Int = x + y

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

Scroll to Top