Table of contents
1.
Introduction
2.
What is Lambda?
3.
What is not a Lambda?
4.
Return Type of Lambda Expression
5.
Type Expression in Lambda
6.
Complex Lambda Expression
7.
FAQs
8.
Key Takeaways
Last Updated: Mar 27, 2024

Kotlin Lambda Expression

Author Rahul Sain
2 upvotes
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

While writing code, we may encounter code that looks like a function but doesn't have a fun keyword to declare it as a function.

These are called Lambda Expressions, and they are widely used in Android Development.

In this article, we will learn about Kotlin Lambda Expression and its need to use them. But before jumping into Lambda, we would strongly recommend learning about Kotlin Functions.

What is Lambda?

Lambda are one of the types of function literals. They are extensively used as a function not defined by a fun keyword, whereas used as part of an expression. As these functions don't require a name, we can use them to assign variables and use them as a function parameter.

Let’s try to explain this with an example.

fun main() {
   val lambda = { println("Hello Kotlin!") }
   lambda()
}


Here, we have assigned a Unit type (equivalent to void in Java) to lambda variable, which will print Hello Kotlin!

In short, we can assume that lambda has a value that will print Hello Kotlin!, and we write lambda() for calling this variable.

Now, let us look into another example of lambda expression.

fun main() {
   val sum: (Int, Int) -> Int = { n1: Int, n2: Int -> n1 + n2 }
   println(sum(5,6))
}

Here we have a sum variable with two Integer type parameters that we will pass while calling this variable. This variable will return the Integer type value as the output.

Output:

11

Here we have supplied 5 and 6 as two parameters in the sum variable and the lambda expression. We are using these two values and returning their sum.

So, after discussing the above example, we can conclude that the syntax of lambda expression would be

Source programiz

val lambda : return_type = { input_argument_list -> do_something_with_input }

Here, there is something to note about lambdas expression. Curly brackets are always used to wrap a lambda expression. Code body is always followed by -> symbol. Defining the data type of the lambda is optional.

val sum: (Int, Int) -> Int = { n1, n2 -> n1 + n2 }

Here, we have eliminated the Argument Datatype Declaration in the above example.

Lambdas can be puzzling at times because they can be written and utilized in a variety of ways, making it difficult to determine whether something is a lambda or not. The following snippet is an example of this:

fun main() {
  val filterArr = listOf(1, 2, 3, 4, 5, 6,7,8,9,10).filter({ it % 2 == 0 })
  println(filterArr)
}

This example filters out even numbers from the numbers from 1 to 10. Here we have used it operator, a simple parameter passing to the expression. Here we are iterating through each number in the given list to represent that number.

Output:

[2, 4, 6, 8, 10]

What is not a Lambda?

If you wonder how to distinguish between a lambda and a regular function, you are on the right track.

fun main() {
   val student = Student("Coding Ninjas",10)
   student.printNameWithMarks()
}

 
class Student(private val name: String, private val score: Int) {
   fun printNameWithMarks() {
       println(name + score)
   }
}

Output:

Coding Ninjas10

The above example is one such example here. We can see that lambdas are not class or function bodies. They are simply a part of basic syntax declaration.

fun main() {
  val number = 10
  val no = if(number % 2 == 0) {
      "$number is Even"
  } else {
      "$number is Odd"
  }
  println(no)
}

Output:

10 is Even

Here, it might look like lambda, but it isn't. Also, the if-else block doesn't represent a function, so we can say that this is not a lambda expression.

Return Type of Lambda Expression

Here is a modified version of the above example, but we are using lambda here.

fun main() {
  val no = fun(number: Int): String {
      return if (number % 2 == 0) {
          "$number is Even"
      } else {
          "$number is Odd"
      }
  }
  println(no(1001))
}

Here we have made no variable that takes a function with number as a parameter. Then we will return the String according to the condition.

Note: If you want to learn more about If Else, head over to this article.

Type Expression in Lambda

Let us now understand different types of Lambdas expressions. First, look at the example below.

fun main() {
  val noArguments = { println("0") }
  val oneArgument = { a: String -> println(a) }
  val twoArguments = { a: Int, b: String -> println("$a + $b") }
  val multipleArguments = { a: String ->
      if (a.isEmpty()) {
          println("$a is empty")
      } else {
          println("$a is not empty")
      }
  }
  noArguments.invoke()
  oneArgument("one")
  twoArguments(2, "two")
  multipleArguments("codingNinjas")
}

Here we have defined different argument types. Note that we have used invoke() to run a lambda expression that has no arguments.

We can give any number of arguments in lambda expression or define any multiple statement lambda expression.

Output:

0
one
2 + two
codingNinjas is not empty

Complex Lambda Expression

Lambdas Expression can be easy to read when it has one or two arguments, but It can go complex once using it with other functions.

fun main() {
  println(listOf(1, 2, 3, 4).fold(1) { n1, n2 -> n1 * n2 })
}

Here, we are using the fold function, which will start from index 0, and the default value of fold would be one as we have supplied in fold(1). Here, we have applied lambda expression with two arguments: the current item and the contemporary accumulated item. This code will multiply all of the items in the list and get 24 as output.

The above output is one of the examples of trailing lambdas. If the lambda is the only argument in the call, we can omit the parentheses entirely.

fun main() {
  run { println("Only Argument") }
}

FAQs

  1. Why is there a need for Lambda Expression?
    A lambda expression is a reduced form of a function. It can be supplied as a parameter, saved as a variable, or returned as a value. It is widely used in those interfaces where there is only one abstract method.
     
  2. Can we pass Lambda as a Function Expression?
    In Kotlin, we can pass Lambda Expression in the function argument. We can also give Lambda Expression in a nested lambda expression.
     
  3. Can we call Lambda Expression an Anonymous Function?
    Yes, lambda expressions and anonymous functions are both function literals. We can call lambda expressions anonymous functions.

Key Takeaways

Cheers if you reached here!! 

The purpose of this article was to introduce you to the Kotlin Lambda Expression, the basic syntax of using this expression and understand the need for Lambda Expression in Android Development.

If you want to learn more about Kotlin Higher-Order and Inline Function in Kotlin, then you can jump to this article which covers them in great detail.

However, learning never stops, and there is more to learn. So head over to our Android Development Course on the Coding Ninjas Website to dive deep into Android Development and build future applications. Till then, Happy Learning!

Live masterclass