EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

Scala High Order Functions

By Arpit AnandArpit Anand

Home » Software Development » Software Development Tutorials » Scala Tutorial » Scala High Order Functions

Scala High Order Functions

Introduction to Scala High Order Functions

High Order Functions, let us first look on what high ordered functions are. A function that takes on other functions as a parameter or in the result returns a function are basically known as High Order Functions. We can pass a function as an argument of other function. Or simply can wait for Scala function to return the function.

We can also define our own High Order Functions by just defining a function and passing that function to other functions to achieve the desired result. In Object-Oriented programming when a method is parameterized with a function it generally can leak the object’sinternal state breaking the encapsulation property for that object. Here internal state refers to the internal property of an object. A map can be the best example that uses Scala High Order Functions. How Map uses that we will check that with an example later.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Definitely using High Order Functions minimize the lines of code making the code easier to understand and clean. We can also achieve function composition with the help of High Order Functions, Function composition comes with the part that shows the utilization of two composed functions.

We can also make anonymous function, function having no name still being used as function and lambda function with the help of this Scala High Order Functions.

Now let us see what an anonymous function is, sometimes there are lots of small functions that makes it tedious for the programmer to name and define each and every function so we make use of anonymous function.

Example

let us check with an example:-

object Demo {
def main(args: Array[String]) {
val str = "abc";
println(str)
}
}

Popular Course in this category
Scala Programming Training (3 Courses,1Project)3 Online Courses | 9+ Hours | Verifiable Certificate of Completion | Lifetime Validity | 1 Project
4.5 (5,543 ratings)
Course Price

View Course

Related Courses
Programming Languages Training (41 Courses, 13+ Projects, 4 Quizzes)All in One Software Development Bundle (600+ Courses, 50+ projects)

Scala Higher Order Functions 1-1

We can directly write this as-

object Demo {
def main(args: Array[String]) {
println("abc")
}
}

Scala Higher Order Functions 1-2

String being an Literal allows us to write the function without any name these are known as Anonymous Functions.

Function Syntax

(x: Int ) => x*x

where x:int is the parameter and x*x is the body here. Now let us check for some example for Scala High Order Functions and look how it works programmatically. As discussed Map operation is one of the classic example for High Order Functions.

Code:

object Demo {
def main(args: Array[String]) {
val list = List(2,3,4)
println(list)
}
}

Scala Higher Order Functions 1-3

object Demo {
def main(args: Array[String]) {
val list = List(2,3,4)
def sum =(x:Int) => x+2            // Defining a Function sum that adds 2 with the required functions
def mulitply = (x: Int ) => x*2   //Defining another function that multiplies with the required function.
val cList = list.map(x => sum(x))  // Using the Function with Map Function
println(cList)
}

Scala Higher Order Functions 1-4

}
object Demo {
def main(args: Array[String]) {
val list = List(2,3,4)
//println(list)
def sum =(x:Int) => x+2            // Defining a Function sum that adds 2 with the required functions
def mulitply = (x: Int ) => x*2   //Defining another function that multiplies with the required function.
val cList = list.map(x =>mulitply(x))   // Using again the same function
println(cList)
}
}

Scala Higher Order Functions 1-5

here we can see that from the above code within the Map Function we used the function that was defined and map Function uses that function value to all the elements in the list. We also can create our own Higher Order Function let us check with an example:-

Code:

object Demo {
def main(args: Array[String]) {
def add(f: (Int, Int) => Int,a: Int, b:Int): Int = f(a,b)
val squareSum = (x: Int, y: Int) => (x*x + y*y)
println(squareSum)
}

function 2

}
object Demo {
def main(args: Array[String]) {
def add(f: (Int, Int) => Int,a: Int, b:Int): Int = f(a,b)
val squareSum = (x: Int, y: Int) => (x*x + y*y)
val squaredSum = add(squareSum, 1, 2)
println(squaredSum)
}
}

function 3

Here we can see that the function add takes the function Square sum as the parameter defined by us and gives the required results over. The function first goes to the square sum value with the values assigned to them and then do the operations over the every element needed.

Passing Lambda Expression as the High Order Functions

We can create anonymous function either by using => or _  wild card in scala.

Code:

object Demo {
def main(args: Array[String]) {
var result = (a:Int ,b:Int ) => a+b  // here we made an anonymous function using =>
println(result)
}
}

function 2-2

bject Demo {
def main(args: Array[String]) {
var result1 = (_:Int)+(_:Int)                                            //here using it as _ (underscore)
println(result1(1,2))
}
}

Scala Higher Order Functions 1-6

object Demo {
def main(args: Array[String]) {
var result = (a:Int ,b:Int ) => a+b  // here we made an anonymous function using =>
var result1 = (_:Int)+(_:Int)         //here using it as _ (underscore)
println(result(1,2))
}
}

Scala Higher Order Functions 1-7

Here we will can see that we can make an anonymous function and call that back with the same value over.

Benefits of Using Anonymous Functions With Scala

With the help of Anonymous Function we can separate different pieces of functionality. A higher order function using anonymous function doesn’t knows that how the function work, this allows the flexibility to compute arguments and concerned only with these arguments used and the return types. Lambda expression are simply the reference to the Anonymous Functions.

Note: Anonymous functions are also called as syntactic sugar, reference with they can be also expressed using def making them Anonymous functions.

Conclusion

Here from the above article, we checked that the use of high order function for Scala, a function taking other function as an argument or returning the function over there can be called as High Order Function making the code base easy and understandable for operations.

Also, we saw the examples showing how can we use these high order functions in different ways. Also, we get to know about the anonymous functions how we can also pass them as the high order functions over.

Recommended Articles

This is a guide to Scala High Order Functions. Here we discuss introduction to Scala High Order Functions with all the benefits and respective examples. You can also go through our other related articles to learn more –

  1. Scala Data Types
  2. Scala Versions
  3. Scala vs Java
  4. Break in Scala

All in One Software Development Bundle (600+ Courses, 50+ projects)

600+ Online Courses

50+ projects

3000+ Hours

Verifiable Certificates

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
Scala Tutorial
  • Advanced
    • Constructors in Scala
    • Scala Class Constructor
    • Scala Abstract Class
    • Scala String
    • Scala Collections
    • Scala High Order Functions
    • Scala Date Function
    • Scala Stream
    • Scala Class
    • Scala Function
    • Scala Closure
    • Scala Range
    • Scala Either
    • Scala Random
    • Scala Tuples
    • Scala Partial Function
    • Scala Split
    • Scala Finds
    • Scala List
    • Scala Trait
    • Scala Try Catch
    • Scala Regex
    • Scala Vector
    • Scala Seq
    • Scala Byte
    • Scala ListBuffer
    • Scala ArrayBuffer
    • Scala flatMap
    • Scala HashMap
    • Scala Map Function
    • Scala SortBy
    • Scala Some
    • Scala Generic
    • Scala getOrElse
    • Scala REPL
    • Scala Logging
    • Scala Lambda
    • Scala Queue
    • Scala Set
    • Scala Singleton
    • Scala groupBy
    • Scala reduce
    • Scala filter
    • Scala Option
    • Scala Native
    • Scala DataFrame
    • Scala Anonymous Function
    • Scala Read File
    • Scala Write to File
    • Scala Pattern Matching
    • Scala ClassTag
    • Scala Synchronized
    • Scala zipwithindex
    • Scala Interview Questions
  • Basics
    • What is Scala?
    • Uses of Scala
    • Scala Versions
    • Scala Data Types
    • Scala Companion Object
    • Scala Operators
    • Scala: The Functional Approach
    • Scala Object
    • Scala Implicit
    • Scala IDE
  • Control Flow
    • Scala if else
    • Break in Scala
    • Scala for Loop
    • Scala foreach
    • Scala While Loops

Related Courses

Scala Programming Training Course

Programming Language Course

Software Development Course Training

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - Scala Programming Training Course Learn More