
- Scala - Home
- Scala - Overview
- Scala - Features
- Scala - Environment Setup
- Scala - Build Tool (SBT)
- Scala - REPL
- Scala - Dot & Dotty
- Scala - Basic Syntax
- Scala - Hello World Program
- Scala - Identifiers
- Scala - Keywords
- Scala - Comments
- Scala - Code Blocks
- Scala - Semicolon
- Scala - Constructs
- Scala - Expressions
- Scala - Input and Output
- Scala - Optional Braces
- Scala - Underscore (_)
- Data Types and Variables
- Scala - Data Types
- Scala - Type Bounds
- Scala - Context Bound
- Scala - Variances
- Scala - Type Hierarchy
- Scala - Variables
- Scala - Variable Scopes
- Scala - Literals
- Scala - Numeric Types
- Scala - Boolean Types
- Scala - Char Type
- Scala - Unit Types
- Scala - Strings
- Scala - Arrays
- Scala - Null Type
- Scala - Nothing
- Scala - Any Type
- Scala - AnyRef Type
- Scala - Unified Types
- Scala - Dates and Times
- Scala - Ranges
- Scala - Multidimensional Arrays
- Scala - WrappedArray
- Scala - StringBuilder
- Scala - String Interpolation
- Scala - StringContext
- Scala - Type Casting
- Scala var vs val
- Scala Operators
- Scala - Operators
- Scala - Rules for Operators
- Scala - Arithmetic Operators
- Scala - Relational Operators
- Scala - Logical Operators
- Scala - Bitwise Operators
- Scala - Assignment Operators
- Scala - Operators Precedence
- Scala - Symbolic Operators
- Scala - Range Operator
- Scala - String Concatenation Operator
- Scala Conditional Statements
- Scala - IF ELSE
- Scala - IF-ELSE-IF-ELSE Statement
- Scala - Nested IF-ELSE Statement
- Scala Loop Statements
- Scala - Loop Statements
- Scala - while Loop
- Scala - do-while Loop
- Scala - Nested Loops
- Scala - for Loop
- Scala - break Statement
- Scala - yield Keyword
- Scala Classes & Objects
- Scala - Classes & Objects
- Scala - Constructors
- Scala - Auxiliary Constructor
- Scala - Primary Constructor
- Scala - This Keyword
- Scala - Nested Classes
- Scala - Getters and Setters
- Scala - Object Private Fields
- Scala - Singleton Object
- Scala - Companion Objects
- Scala - Creating Executable Programs
- Scala - Stateful Object
- Scala - Enumerations
- Scala - Polymorphism
- Scala - Access Modifiers
- Scala - Apply Method
- Scala - Update Methods
- Scala - UnapplySeq Method
- Scala - Inheritance
- Scala - Extending a Class
- Scala - Method Overloading
- Scala - Method Overriding
- Scala - Generic Classes
- Scala - Generic Functions
- Scala - Superclass Construction
- Scala Methods & Functions
- Scala - Functions
- Scala - Main Methods
- Scala - Functions Call-by-Name
- Scala - Functions with Named Arguments
- Scala - Function with Variable Arguments
- Scala - Recursion Functions
- Scala - Default Parameter Values
- Scala - Functions without Parameters
- Scala - Implicit Parameters
- Scala - Higher-Order Functions
- Scala - Nested Functions
- Scala - Extension Methods
- Scala - Anonymous Functions
- Partially Applied Functions
- Scala - Lazy Val
- Scala - Pure Function
- Scala - Currying Functions
- Scala - Control Abstractions
- Scala - Corecursion
- Scala - Unfold
- Scala - Tail Recursion
- Scala - Infinite Sequences
- Scala - Dynamic Invocation
- Scala - Lambda Expressions
- Scala Collections
- Scala - Collections
- Mutable and Immutable Collections
- Scala - Lists
- Scala - Sets
- Scala - Maps
- Scala - TreeMap
- Scala - SortedMap
- Scala - Tuples
- Scala - Iterators
- Scala - Options
- Scala - Infinite Streams
- Scala - Parallel Collections
- Scala - Algebraic Data Types
- Scala Pattern Matching
- Scala - Pattern Matching
- Scala - Type Patterns
- Scala - Exception Handling
- Scala - Extractors
- Scala - Regular Expressions
- Scala Files I/O
- Scala - Files I/O
- Scala Advanced Concepts
- Scala - Closures
- Scala - Futures
- Scala - Promises
- Scala - Traits
- Scala - Trait Mixins
- Scala - Layered Traits
- Scala - Trait Linearization
- Scala - Sealed Traits
- Scala - Transparent Traits
- Scala - Literal Type Arithmetic
- Scala - Inline keyword
- Scala - Def, Var & Val
- Scala - Dropped Features
- Scala - BDD Testing
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.