Scala - Lambda Expressions



This chapter takes you through the concept of lambda expressions in Scala programming. Lambda expressions are used to define functions without giving them a name. Lambda expressions are also known as anonymous functions. Generally, these are used for passing around as arguments to higher-order functions like map, filter, and reduce.

Lambda Expressions

Lambda expressions are a shorthand for defining functions directly in the code. Lambda expressions are functions that do not need to be reused elsewhere. Your code will be more concise and readable.

A lambda expression is an anonymous function defined using the => symbol. The left side of => contains the parameters and the right side has the expression and statements to be executed.

Syntax

The syntax of lambda expressions in Scala is -

(parameters) => expression

Where,

  • parameters are optional if the lambda takes no arguments and can be inferred.
  • expression is the body of the function.

Example of Lambda Expressions

The following example shows defining and using a lambda expression in Scala programming -

object Demo {
   def main(args: Array[String]): Unit = {
      val add = (x: Int, y: Int) => x + y
      println(add(3, 4)) 
   }
}

Save the above program in Demo.scala. Use the following commands to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

7

In the example, the lambda expression (x: Int, y: Int) => x + y defines an anonymous function that takes two integers and returns their sum.

Advantages of Lambda Expressions

There are various advantages of lambda expressions. You can define functions in a concise way that does not require defining named functions. Your code will be more readable when you work with short, simple functions that are used in only one place. You can pass lambda expressions as arguments to higher-order functions, stored in variables, returned from other functions, etc. This provides great flexibility in functional programming.

Lambda Expressions with Collections

Lambda expressions are used with collections to perform various operations, like, mapping, filtering, and reducing.

Syntax

The syntax of using lambda expressions with collections is -

collection.method((parameters) => expression)

Example

Consider the example of using lambda expressions with collections in Scala programming -

object Demo {
   def main(args: Array[String]): Unit = {
      val numbers = List(1, 2, 3, 4, 5)
      val doubledNumbers = numbers.map(x => x * 2)
      println(doubledNumbers) 
   }
}

Save the above program in Demo.scala. Use the following commands to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

List(2, 4, 6, 8, 10)

In the example, the lambda expression x => x * 2 is used with the map method to double each element in the list.

Single-Parameter Lambda Expressions

You can ignore the parentheses around the parameter for lambda expressions with a single parameter.

Syntax

The syntax of single-parameter lambda expression is -

parameter => expression

Example

Consider the example of a single-parameter lambda expression in Scala programming -

object Demo {
   def main(args: Array[String]): Unit = {
      val numbers = List(1, 2, 3, 4, 5)
      val squaredNumbers = numbers.map(x => x * x)
      println(squaredNumbers) 
   }
}

Save the above program in Demo.scala. Use the following commands to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

List(1, 4, 9, 16, 25)

In the example, the lambda expression x => x * x squares each element in the list.

Lambda Expressions with Higher-Order Functions

You can use lambda expressions as arguments to higher-order functions. These are functions that either take other functions as parameters or return these or both.

Syntax

The syntax of using lambda expressions with higher-order functions is -

higherOrderFunction((parameters) => expression)

Example

Consider the example of using lambda expressions with higher-order functions in Scala programming -

object Demo {
   def applyFunction(f: (Int, Int) => Int, x: Int, y: Int): Int = f(x, y)

   def main(args: Array[String]): Unit = {
      val result = applyFunction((x, y) => x * y, 3, 4)
      println(result) 
   }
}

Save the above program in Demo.scala. Use the following commands to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

12

In the example, the lambda expression (x, y) => x * y is passed as an argument to the higher-order function applyFunction.

Placeholder Syntax for Lambda Expressions

Scala provides a placeholder syntax for lambda expressions. You can use underscores (_) as placeholders for parameters. So, your lambda expressions will be more concise and readable.

Syntax

The syntax of placeholder lambda expressions is -

_ + _

Example

Consider the example of using placeholder syntax for lambda expressions in Scala programming -

object Demo {
   def main(args: Array[String]): Unit = {
      val numbers = List(1, 2, 3, 4, 5)
      val incrementedNumbers = numbers.map(_ + 1)
      println(incrementedNumbers) 
   }
}

Save the above program in Demo.scala. Use the following commands to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

List(2, 3, 4, 5, 6)

In the example, the placeholder syntax _ + 1 is used with the map method to increment each element in the list.

Lambda Expressions and Type Inference

You can use inference system that automatically deduces the types of parameters in lambda expressions. It reduces the need for explicit type annotations.

Syntax

The syntax of lambda expressions with type inference is -

parameters => expression

Example

Consider the example of lambda expressions with type inference in Scala programming -

object Demo {
   def main(args: Array[String]): Unit = {
      val numbers = List(1, 2, 3, 4, 5)
      val filteredNumbers = numbers.filter(_ % 2 == 0)
      println(filteredNumbers) 
   }
}

Save the above program in Demo.scala. Use the following commands to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

List(2, 4)

In the example, the lambda expression _ % 2 == 0 filters the list to keep only the even numbers.

Lambda Expressions for Function Composition

You can compose lambda expressions to create more complex functions by combining simpler ones.

Syntax

The syntax of function composition using lambda expressions is -

val composedFunction = (parameters) => expression1 andThen expression2

Example

Consider the example of using lambda expressions for function composition in Scala programming -

object Demo {
   def main(args: Array[String]): Unit = {
      val addOne = (x: Int) => x + 1
      val multiplyByTwo = (x: Int) => x * 2
      val composedFunction = addOne andThen multiplyByTwo
      println(composedFunction(3)) 
   }
}

Save the above program in Demo.scala. Use the following commands to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

8

In the example, the composedFunction first increments the input by 1 and then multiplies the result by 2.

Lambda Expression with Curly Braces

You can write lambda expressions using curly braces {} for multiple lines of code.

Syntax

The syntax of lambda expression using curly braces is -

(parameters) => {
   // Code block
   expression1
   expression2
   // ...
}

Example

The following example uses a lambda expression with curly braces in Scala programming -

object Demo {
   def main(args: Array[String]): Unit = {
      val greet = (name: String) => {
         val message = s"Hello, $name!"
         println(message)
      }

      greet("John")

   }
}

Save the above program in Demo.scala. Use the following commands to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

Hello, John!

In the example, greet is a lambda expression that takes a name parameter. It constructs a greeting message using string interpolation and prints it.

Lambda Expressions Summary

  • Lambda expressions are a concise way to define anonymous functions using the =>
  • Lambda expressions enhance code readability, conciseness, and flexibility. These eliminate the need for named functions.
  • Lambda expressions are used with collections, higher-order functions, and in function composition.
  • These support single-line expressions and code blocks with curly braces for multiple lines.
  • You can use placeholder syntax and type inference with lambda expressions for more concise and easier to use.
  • Lambda expressions can be composed to create more complex functions by combining simpler ones.
Advertisements