Open In App

Working with Anonymous Function in Kotlin

Last Updated : 20 Dec, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

In Kotlin, we can have functions as expressions by creating lambdas. Lambdas are function literals that is, they are not declared as they are expressions and can be passed as parameters. However, we cannot declare return types in lambdas. Although the return type is inferred automatically by the Kotlin compiler in most cases, for cases where it cannot be inferred on its own or it needs to be declared explicitly, we use the anonymous functions. In this article, we will see how to use anonymous functions. Before that we have some:

Prerequisites for this Article:

Basic Idea of these:

  • Lambda Expression (it is a short way to define a function.)
  • Anonymous Function (it is an alternative way to define a function.)

Refer to this article: Lambdas Expressions and Anonymous Functions

Example

We will learn about anonymous functions Step-by-Step with the help of some examples:

Let’s start by declaring a function as a lambda:

Kotlin




fun main(args: Array<String>){
    val funMultiply = {a : Int, b : Int-> a * b} 
    printIn(funMultiply(6,4))
    val funSayHi = {name : String->println("Hi $name")}
    funSayHi("geek")
}


In the preceding code block, we have declared two lambdas: one (funMultiply) that takes two integers and returns an integer, and another (funSayHi) lambda that takes a string and returns a unit-that is, it returns nothing. Although in the preceding example we did not need to declare the type of arguments and return type, in some cases we need to explicitly declare the argument types and return types. We do that in the following way, by means of an anonymous function:

Kotlin




fun main (args: Array<String>){
  var funMultiply = fun (a: Int, b: Int) : Int {return a*b}
  printin (funMultiply (6,4))
  fun (name : String) : Unit = println ("Hi $name")
}


So now we have a general idea of how anonymous functions work. Now, let’s try and pass one in another function-that is, we will try a high-order function. Check out this code snippet:

Kotlin




fun main (args: Array<String>){
    var funMultiply = fun(a: Int, b: Int) : Int { return a*b }
    var funSum = fun(a: Int, b: Int) : Int { return a+b }
    performMath (6, 4, funMultiply)
    performMath (6, 4, funSum)
}
fun performMath (a : Int, b: Int, mathFun : (Int, Int) -> Int) : Unit
{
    printIn ( "Value of calculation: ${mathFun(a, b)}")
}


So basically, an anonymous function is declared just like a regular function, but without a name. The body can be an expression, as in the following example, or a block, as in the preceding example. One thing to note is that parameters are always passed inside the parentheses in the case of anonymous functions, unlike in lambda expressions:

Kotlin




fun main (args: Array<String>) {
    performMath (6,4, fun (a: Int, b: Int) : Int = a*b )
    performMath (6,4, fun (a: Int, b: Int) : Int = a+b )
}
fun performMath (a : Int, b: Int, mathFun : (Int, Int) -> Int) : Unit
{
    println ("final value: ${mathFun(a,b)}")
}


  • Another interesting difference between a lambda and an anonymous function is that in a lambda, the return statement returns from the enclosing function, whereas in an anonymous function, it simply returns from the function itself.
  • One can omit the parameter type and return type from an anonymous function as well if it can be inferred on its own.
  • Anonymous functions can access and modify variables inside their closures.

So basically, one can declare an anonymous function just like a regular function without a name (hence, the name anonymous ). It can be an expression or a code block.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads