Kotlin: Function type, Function literal, Lambda expression and Anonymous function
Tags: kotlin, functiontype, functionliteral, lambdaexpression
Published: 2020-05-01 01:15:43

#Function Type

We know data types. Similarly, we have function type too in kotlin.

###Signature / Syntax

```
    Name: (only comma separated data types) -> return data type

    ft: (Int, Int) -> Int
```
{% gist https://gist.github.com/sagarpatel288/bf6bcab9608dddfeb1c9793f8059c054 %}

### How to call / execute a function type?

```kotlin
    ft(1, 2) 

    //OR

    ft.invoke(1, 2)
```
{% gist https://gist.github.com/sagarpatel288/b5413ec61264399901f78d767bb65bda %}

## Usage:

#### Function type as an interface

Like an interface, we can implement a function type in a kotlin class. When we implement a function type, we get a method called “invoke” to override having a similar signature of the implemented function type.

Example:

```kotlin
    //Implementing a function type like an interface
    class ClassName : (Int, Int) -> Int {

    /**We get a method "invoke" to override with similar signature of     
     * function type we implemented
     */
    override fun invoke(p1: Int, p2: Int): Int {
            return p1 + p2
        }
    
    }
```
{% gist https://gist.github.com/sagarpatel288/1ea92a51b6628e6ad4ff5150d8b2e384 %}

#### Function type as a parameter

As a function parameter in a higher order function. The function that takes one or more function types as a parameter/s or/and the function that returns a function type is known as a higher order function.

```kotlin
    fun doSomething(a: Int, b: Int, ft: (Int, Int) -> Int): String {
     
        val result = ft(a, b) //OR ft.invoke(a, b)

        return “doSomething: ” + result
    }
```
{% gist https://gist.github.com/sagarpatel288/5cbff4108cd2feacce2d090711a11ecd %}

There is one thing to remember here:.

**A new function object will be created for each and every function type of a higher order function.**

#### How to call/use/execute such a higher order function?

We know how to call a function but we may not know how to pass a function type argument/s in any higher order function!

We can pass function type arguments using function literal, lambda expression or by anonymous function. Let us check these all one by one.

# Function literal

### Signature / Syntax: 1

```
    { comma separated pascal parameters -> business logic }
```

Example:

```kotlin
    { x: Int, y: Int -> x + y }
```

{% gist https://gist.github.com/sagarpatel288/e8c74442e05c9700437e165b0f0f2dea %}

Note that the last statement in a function literal is considered as a return statement. So, the last statement in a function literal decides the return type.

We can use function literal to pass as a function type argument for higher order function as below:

```kotlin
    //Calling a higher order function 

    println(doSomething(1, 2, {x: Int, y: Int -> x + y})) 

    //prints: doSomething: 3
```

{% gist https://gist.github.com/sagarpatel288/8d2f69af5f99579765cdc502d4bb6f80 %}

OR if the function type parameter is the last parameter in the higher order function, we can write our function literal after the closing function parenthesis as below:

```kotlin
    //Calling a higher order function

    println(doSomething(1, 2){x: Int, y: Int -> x + y})

    //prints: doSomething: 3
```
{% gist https://gist.github.com/sagarpatel288/b41bcb97d99bce107f21f2f135901992 %}

OR if the higher order function has only one parameter or say if the function type parameter is one and only parameter in a higher order function like below:

```kotlin
   //region A higher order function that has one and only function type parameter
    private fun doSomething(ft: (Int, Int) -> Int) {
        val result = ft(1, 2)
        /*...*/
    }
   //endregion
```

{% gist https://gist.github.com/sagarpatel288/c7180f63feb67f40bb677d5ff7ca8f86 %}

While calling such a higher order function, we can omit the function call parentheses like below:

```kotlin
        doSomething { x: Int, y: Int -> x + y }
```

{% gist https://gist.github.com/sagarpatel288/fadbd3700b3d2ccf5db492b5f808f6d1 %}

### Syntax / Signature 2

Also, if the function type is only parameter in a higher order function and if the function type has also only one parameter like below:

```kotlin
 private fun doSomething(ft: (Int) -> String) {
        /*...*/
 }
```
{% gist https://gist.github.com/sagarpatel288/5fde0ce9a23e211c565755cf9788c14e %}

While passing such a function literal, in addition to function call parentheses, we can also omit the parameter and an arrow `->` ! We just write core business logic between curly braces and we can access our single parameter through the keyword it like below:

```kotlin
doSomething { "$it" }
```

{% gist https://gist.github.com/sagarpatel288/1befa2159b6ed4571eb83137783fedfb %}

And if the higher order function has only one function type parameter and the function type has no parameter like below:

```kotlin
private fun doSomethingY(ft: () -> String) {
        /*...*/
}
```
{% gist https://gist.github.com/sagarpatel288/6acfa7819b8390bd3654e620b790cabc %}

We can simply write our business logic between curly braces right after the higher order function name as below:

```kotlin
doSomethingY { "test" }
```
{% gist https://gist.github.com/sagarpatel288/12e62a5686af8fb1098d0818d884f13e %}

### Types:

There are two types of function literals.

1. Lambda expression

2. Anonymous function

# Lambda expression

Lambda expression is just another way to define a function in a short way.

### Signature / Syntax 1

We can either specify explicit function type and let the data type of parameters inferred in below format:

```kotlin
nameOfTheLambda: (explicit function type) = { comma separated parameter: Inferred data type -> business logic }
```

Or we can give explicit type annotation to parameters and let the function type inferred like below format:

```kotlin
nameOfTheLambda: (inferred function type) = { comma separated parameter: Explicit dataType -> business logic}
```

Or we can write both function type and data type of parameter (but why?) like below:

```kotlin
nameOfTheLambda: (explicit function type) = { comma separated parameter: Explicit dataType -> business logic}
```

Let us see an example:

```kotlin
    /**
     * nameOfTheLambda: function type 
     * = { comma separated pascal parameters -> business logic }
     */

    val lambda: (Int, Int): Int = { x: Int, y: Int -> x + y }
```
{% gist https://gist.github.com/sagarpatel288/e2e498f6efbb93b37a5ca8979ba4516d %}

### Signature / Syntax 2 for special case

**If a lambda has only one parameter, we can omit everything except a business logic inside the curly braces and we can access the single argument using the keyword: _it_**

Example:

Suppose we have a lambda expression like below:

```kotlin
    val lambdaIncrement: (Int): Int = { x: Int -> x + 1 }
```
{% gist https://gist.github.com/sagarpatel288/6178d1e0d675c794b682ac00db199a21 %}

We can write the equivalent lambda as below:

```kotlin
    val lambdaIncrement: (Int): Int = { it + 1 }
```
{% gist https://gist.github.com/sagarpatel288/f570defada29c87e1b6f984ebf4187cb %}

Summary for a lambda expression having a single parameter

{% gist https://gist.github.com/sagarpatel288/4de84d7ab3fe6b0ab867b36b970ea06d %}

### Usage: How to call / execute / use lambda expression

We can use above lambda expression directly like below:

```kotlin
    println(lambda(1,2)) //prints: 3
```
{% gist https://gist.github.com/sagarpatel288/3d7a7badb23876d48829aeef1d1d2301 %}

OR we can pass a lambda as a function type argument to a higher order function like below:

```kotlin
    println(doSomething(1, 2, lambda)) //prints: doSomething: 3
```

{% gist https://gist.github.com/sagarpatel288/efcf9786f062c36cb92aee1a6b33159e %}

Sometimes, the common term “_lambda_” is used to represent a function type, function literal or a lambda expression.

# Anonymous function

### Signature / Syntax

```kotlin
    //fun(comma separated pascal parameters) = business logic

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

{% gist https://gist.github.com/sagarpatel288/2978c07f983fd130fb197efd497c0f80 %}

We can store an anonymous function in a variable like below:

```kotlin
    val anonymousFunction: (Int, Int): Int = fun(x: Int, y: Int) = x + y
```

{% gist https://gist.github.com/sagarpatel288/4dcc7a554d85dc74e4f3ad8cb0d1ea9f %}

### Usage: How to use an anonymous function

We use an anonymous function as an argument for a higher order function like below:

```kotlin
    println(doSomething(1, 2, fun(x: Int, y: Int) = x + y )) 

    //prints: doSomething: 3
```
{% gist https://gist.github.com/sagarpatel288/dca081770c891787e7eca1b0dcd4d4dc %}

We can use an anonymous function through a variable to pass as an argument in a higher order function as below:

```kotlin
    println(doSomething(1, 2, anonymouseFunction) 

    //prints: doSomething: 3
```
{% gist https://gist.github.com/sagarpatel288/661c32e54f205899ab54f3d517307d0f %}

That’s all! If you have read this article, if you find this article helpful, you can click on that heart icon 😉

Applauds and creative critics are always welcome 😇

In [next article](https://dev.to/srdpatel/kotlin-extension-function-1dd7), we will learn about **Extension function and Receiver type**.

Thanks for reading the article! Have a great day 😇

# Let us be Connected

[https://www.linkedin.com/in/srdpatel](https://www.linkedin.com/in/srdpatel)

[https://twitter.com/iSrdPatel](https://twitter.com/iSrdPatel)

Tags: kotlin, function type, function literal, lambda expression, anonymous function, higher order function