Instruction

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Lambda Expressions

In Kotlin, a lambda expression is a function without a name. It’s used to define a code block that can be passed as an argument to a function or stored in a variable.

Defining a Lambda Expression

To define a lambda expression, you enclose a block of code in curly braces: {}. Then, you can assign the code block to a variable, such as the following:

val myFirstLambda = { println("This is my first lambda") }

fun main() {
  myFirstLambda()
}
This is my first lambda

Lambda Expressions With Arguments

A lambda expression can take arguments and return a value. The syntax of a lambda expression taking two arguments of type Int looks like this:

val myLambda = { num1: Int, num2: Int ->
  val sum = num1 + num2
  // The value stored in sum is the value that will be returned when the `myLambda` lambda expression is executed since it's the last statement in the lambda.
  sum
}

Type Inference

Kotlin’s type inference enables the compiler to evaluate the type of a lambda, such as in the myLambda expression:

val myLambda = { num1: Int, num2: Int ->
  val sum = num1 + num2
  sum
}
val stringLambda: (String) -> Int = { name: String ->
  name.length
}

See forum comments
Download course materials from Github
Previous: Introduction Next: Demo