DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Mastering Advanced Aggregations in Spark SQL
  • Thermometer Continuation in Scala
  • Deploying a Scala Play Application to Heroku: A Step-by-Step Guide
  • Upgrading Spark Pipelines Code: A Comprehensive Guide

Trending

  • Developers Beware: Slopsquatting and Vibe Coding Can Increase Risk of AI-Powered Attacks
  • How To Build Resilient Microservices Using Circuit Breakers and Retries: A Developer’s Guide To Surviving
  • Tired of Spring Overhead? Try Dropwizard for Your Next Java Microservice
  • How to Use AWS Aurora Database for a Retail Point of Sale (POS) Transaction System
  1. DZone
  2. Coding
  3. Languages
  4. Higher-Order Functions in Scala

Higher-Order Functions in Scala

Let's take a look at how to use higher-order functions in Scala.

By 
Jyoti Sachdeva user avatar
Jyoti Sachdeva
·
Updated Dec. 19, 18 · Tutorial
Likes (7)
Comment
Save
Tweet
Share
49.8K Views

Join the DZone community and get the full member experience.

Join For Free

In this blog, I’m going to explain higher-order functions.

A higher-order function takes other functions as a parameter or returns a function as a result.

This is possible because functions are a first-class value in Scala. What does that mean?

It means that functions can be passed as arguments to other functions, and functions can return other functions.

The map function is a classic example of a higher order function.

val list = List(1,2,3)


Let’s define a function that doubles each value that is given to it.

def doubleValue = (x: Int) => x * x
doubleValue: Int => Int

val doubledList = list.map(x => doubleValue(x))


This example will call List(1,2,3).map(x => doubleValue(x)) and gives us a list with values (1, 4, 9). The function map will be called on each element of the list that will be passed to doubleValue.

We can also give it an anonymous function.

List(1,2,3) map (x => x + 1)


Amap is a function that takes another function(x => x+1) and a list as its arguments and applies the given function to all the elements of the list.

Create Our Own Higher-Order Function:

Example 1

def addition(f: (Int, Int) => Int,a: Int, b:Int): Int = f(a,b)


This addition takes a higher-order function as an input, which, in turn, takes two integers as an input and returns an integer.

val squareSum = (x: Int, y: Int) => (x*x + y*y)
val cubeSum = (x: Int, y: Int) => (x*x*x + y*y*y)
val intSum = (x: Int, y: Int) => (x + y)

val squaredSum = addition(squareSum, 1, 2)
val cubedSum = addition(cubeSum, 1, 2)
val normalSum = addition(intSum, 1, 2)


Note that:

  • addition(squareSum, 1, 2) will call squareSum(1,2).
  • addition(cubeSum, 1, 2) will call cubeSum(1,2).
  • addition(intSum, 1, 2) will call intSum(1,2).

Example 2

def applyPatternToText(text:String,f:String => String): String = {
f(text)
}


The applyPatternToText function takes another function as a parameter.

def appendTag(data:String): String => String = {
_ : String => s"$data"
}


The appendTag function returns a function itself.

val message = "scala"
println( applyPatternToText(message, appendTag(message)))


This will call applyPatternToText (“scala”,appendTag(“scala”)).

f:String => String will be replaced by appendTag(“scala”).

 appendTag(“scala”) will print scala.

Example 3

Let’s take another example to find the sum of a list and product of a list using the higher-order function:

def operateList(list: List[Int], f: (Int, Int) => Int, operation: String): Int = {
def inner(list: List[Int], result: Int): Int = {
list match {
case head :: tail => inner(tail, f(head, result))
case Nil => result
}
}

operation.toLowerCase match {
case "product" => inner(list, 1)
case "sum" => inner(list, 0)
}
}


The operateList (List(1,2,3),(a, b) => a + b, “sum”) will call the inner(List(1,2,3),0).

After match condition, the next call will be inner(List(2,3),f(1,0)), which will give inner(List(2,3),1).

The next call would be inner(List(3),f(2,1)), which will give inner(List(3),3). Then, the next call would be inner(Nil,f(3,3)), which will give inner(Nil,6).

The final result would be 6!

Scala (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Mastering Advanced Aggregations in Spark SQL
  • Thermometer Continuation in Scala
  • Deploying a Scala Play Application to Heroku: A Step-by-Step Guide
  • Upgrading Spark Pipelines Code: A Comprehensive Guide

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!