
- 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 - Higher-Order Functions
Higher-order functions are functions that can take other functions as parameters. These may return functions as results. So, you can create flexible and reusable code.
Higher-Order Functions
Higher-order functions are functions that operate on other functions. These higher order functions take other functions as arguments or return other functions. So, there can be higher levels of abstraction. Hence more concise and expressive code.
Definition
Higher-order function is a function that does at least one of the following -
- Takes one or more functions as arguments.
- Returns a function as its result.
Syntax
The syntax of higher order function in Scala is -
def higherOrderFunction(f: (ParameterType) => ReturnType, x: ParameterType): ReturnType = { // function body }
Example of Higher Order Functions
The following example shows defining and using a higher-order function that takes another function as an argument -
object Demo { def applyFunction(f: Int => Int, x: Int): Int = { f(x) } def increment(n: Int): Int = { n + 1 } def main(args: Array[String]): Unit = { println(applyFunction(increment, 5)) } }
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
6
In the example, the applyFunction function is a higher-order function. It takes another function f and integer x as arguments. It applies f to x and returns the result. The increment function is defined to add 1 to a given number. The Demo object calls applyFunction with increment and an integer.
Higher-Order Functions with Multiple Functions
There can be multiple functions as parameters in a Higher-order function. So you can perform more complex operations and compositions.
Syntax
The syntax of multiple functions in a higher order function -
def functionName(param1: Type1, param2: Type2 => ReturnType, param3: Type3 => ReturnType, ...): ReturnType = { // function body }
Example
The following example shows using multiple functions as parameters in a higher-order function.
object Demo { def applyFunctions(f1: Int => Int, f2: Int => String, v: Int): String = { f2(f1(v)) } def main(args: Array[String]): Unit = { val result = applyFunctions(x => x * 2, x => s"Result: $x", 5) println(result) // Result: 10 } }
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
Result: 10
In the example, the applyFunctions method takes two functions: f1 and f2, and an integer v. The function f1 is applied to v first, and then f2 is applied to the result of f1.
Returning Functions from Functions
A function can return another function as its result. So this function is known as higher order function. You can create functions dynamically based on input parameters and return them as a function.
Syntax
The syntax for returning function from a function in Scala -
def higherOrderFunction(x: ParameterType): (AnotherParameterType) => ReturnType = { // return a function (y: AnotherParameterType) => { // function body } }
Example
The following example shows defining and using a higher-order function that returns another function in Scala programming -
object Demo { def createMultiplier(factor: Int): Int => Int = { (x: Int) => x * factor } def main(args: Array[String]): Unit = { val multiplyBy2 = createMultiplier(2) println(multiplyBy2(5)) } }
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
10
In the example, the createMultiplier method returns a function that multiplies its input by a given factor. The returned function is then used to multiply the value 5 by 2.
Common Higher-Order Functions in Scala
There are some common higher order functions in Scala.
1. map
The map function is a higher-order function. It applies given function to each element of collection. It returns a new collection with the results.
Syntax
The syntax of the map higher order function -
collection.map(f: (ElementType) => ReturnType): CollectionType
Example
Consider the example of map higher order function in Scala programming -
object Demo { def main(args: Array[String]): Unit = { val numbers = List(1, 2, 3, 4, 5) val doubled = numbers.map(x => x * 2) println(doubled) // List(2, 4, 6, 8, 10) } }
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
List(2, 4, 6, 8, 10)
2. filter
The filter function is a higher-order function. It selects elements of collection that satisfy a given predicate function.
Syntax
The syntax of the filter higher order function -
collection.filter(p: (ElementType) => Boolean): CollectionType
Example
Consider the example of filter higher order function in Scala programming -
object Demo { def main(args: Array[String]): Unit = { val numbers = List(1, 2, 3, 4, 5) val evenNumbers = numbers.filter(x => x % 2 == 0) println(evenNumbers) // List(2, 4) } }
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
List(2, 4)
3. reduce
The reduce function is a higher-order function. It combines elements of collection using a given binary function.
Syntax
The syntax of the filter higher order function -
collection.reduce(f: (ElementType, ElementType) => ElementType): ElementType
Example
Consider the example of reduce higher order function in Scala programming -
object Demo { def main(args: Array[String]): Unit = { val numbers = List(1, 2, 3, 4, 5) val sum = numbers.reduce((a, b) => a + b) println(sum) // 15 } }
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
15
Higher-Order Functions with Anonymous Functions
You can use higher-order functions with anonymous functions (lambdas) for more concise and flexible code.
Syntax
The syntax of the higher order function with anonymous function -
higherOrderFunction((parameters) => { functionBody }, otherArguments)
Example
The following example shows using a higher-order function with an anonymous function in Scala programming -
object Demo { def applyFunction(f: Int => Int, x: Int): Int = { f(x) } def main(args: Array[String]): Unit = { println(applyFunction((n: Int) => n * 2, 5)) // 10 } }
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
10
In the example, the applyFunction function is used with an anonymous function (n: Int) => n * 2 to double the input value. The Demo object calls applyFunction with anonymous function and integer.
Higher Order Functions Summary
- Higher-order functions in Scala are functions that either take other functions as parameters or these return a function as results.
- Higher-order functions provide a way to create more flexible and reusable code.
- You can also use higher-order functions with collections to perform operations like mapping, filtering, and reducing.
- You can use higher-order functions with anonymous functions for more concise and expressive code.