Function Literals in Kotlin (with Examples)

Kotlin function literals

In this article, you will learn about function literals in Kotlin. We’ll explore what they are, and different types of function literals with examples.

Prerequisites:

Let’s get started.

First, What is a Literal?

In programming, a literal is a constant value assigned to a variable.

Example:

val x = 10

Here, val is a keyword, x is a variable name, and 10 is a literal. Since its type is integer, it is called integer literal.

Similarly, we have double literals (example, 12.34), string literals (example, “hello world”), etc…

Literals in programming

What is a Function Literal?

In Kotlin, functions are first-class citizen, which means functions can be assigned to the variables, passed as an arguments or returned from another function.

When we assign a function to a variable, it becomes a function literal. Kotlin provides 2 types of function literals. They are:

  • Lambda Expression
  • Anonymous Function

Lambda Expression:

Lambda expression is a short way to create a function. To define a lambda expression, enclose the method body inside braces.

Example:

val printWelcome = { println("Welcome to SemicolonSpace") }

Here, printWelcome is a variable and { println(“Welcome to SemicolonSpace”) } is a lambda expression.

Kotlin lambda function example

There are two ways to execute the lambda.

  1. Add parentheses after the variable name
  2. Call invoke() method
fun main() {
   val printWelcome = { println("Welcome to SemicolonSpace") }
   printWelcome()
   printWelcome.invoke()
}

Output:

Welcome to SemicolonSpace
Welcome to SemicolonSpace

Lambda expressions accept arguments and return value. Let’s look at the syntax.

Syntax of a Lambda Expression:
Kotlin lambda expression syntax

Example:

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

Here, add takes two integers, performs addition on them, and returns the result (an integer).

The last statement of the method body (a + b) helps the compiler in inferring the return type of the lambda.

Function Types:

Function type is similar to a function signature. It contains parameters and return type. In the above example, (Int, Int) -> Int is the function type.

Kotlin lambda function type

Shorter Syntax:

There are two shorter syntaxes.

1. We can skip the function type.

Example:

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

2. We can skip the data types inside the curly brackets. If you do this, you should include the function type.

Example:

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

Now, let’s look at the different function types.

There are 4 function types depending on the parameters and return type.

1. With Parameters and No Return Value:
val add: (Int, Int) -> Unit = {a, b -> println("Sum = ${a + b}") }
add(20, 30)

Output:

Sum = 50
2. With Parameters and Return Value:
val add: (Int, Int) -> Int = { a, b -> a + b }
println("Sum = ${add(20, 30)}")

Output:

Sum = 50
3. No Parameters and No Return Value:
val message: () -> Unit = { print("Hello World") }
message()

Output:

Hello World
4. No Parameters and Return Value:
val message: () -> String = { "Hello World" }
println(message())

Output:

Hello World

We don’t always need a variable. We can directly use the lambda expression.

Example:

println( {a: Int, b: Int -> a + b}(10, 20) ) // prints 30

Anonymous Function:

It is a function without a name.

Syntax:

Anonymous Function Syntax

Example:

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

println(add(10, 20)) // prints 30

Here, add takes two integers, performs addition on them, and returns the result.

There is also a shorter syntax.

Anonymous Function Syntax Short

Example:

val add = fun(a: Int, b: Int): Int { return a + b }
println(add(10, 20)) // prints 30

If the method body has only one statement, we can omit the return keyword and the braces.

val add = fun(a: Int, b: Int): Int = a + b

Let’s look at the different formats of anonymous functions based on the parameters and return type.

1. With Parameters and No Return Value:
val add = fun(a: Int, b: Int): Unit { print("Sum = ${a + b}") }
add(10, 20)

Output:

Sum = 30

Note: It is optional to specify the Unit (return type).

val add = fun(a: Int, b: Int) { print("Sum = ${a + b}") }
2. With Parameters and Return Value:
val add = fun(a: Int, b: Int): Int { return a + b }
println(add(10, 20))

Output:

30
3. No Parameters and No Return Value:
val message = fun(): Unit { println("Hello World") }
message()

Output:

Hello World
4. No Parameters and Return Value:
val message = fun(): String { return "Hello World" }
println(message())

Output:

Hello World

This is how you can assign functions to the variables. Like I said before, functions are first-class citizen. we can also pass them to other functions. They are called higher-order functions. Here is the article on how to pass functions as parameters in Kotlin.

Leave a Comment