Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Scala: HOF (Higher-Order Function)

DZone's Guide to

Scala: HOF (Higher-Order Function)

Check out this quick read on high-order function in Scala, with examples.

· Java Zone ·
Free Resource

How do you break a Monolith into Microservices at Scale? This ebook shows strategies and techniques for building scalable and resilient microservices.

Scala allows the definition of higher-order function. These are functions that take other functions as parameters, or whose result is a function.

A higher-order function, as opposed to a first-order function, can have one of three forms:

  • One or more of its parameters is a function, and it returns some value.
  • It returns a function, but none of its parameters is a function.
  • Both of the above: One or more of its parameters is a function, and it returns a function.

If you have followed this series, you have seen a lot of usages of higher-order functions of the first type: We called methods like map, filter, or flatMap and passed a function to it that was used to transform or filter a collection in some way. Very often, the functions we passed to these methods were anonymous functions.

Example: [map]

object HOF {

    def main(args: Array[String]) {
      val list = List(
        ("Bala", "S"),
        ("Balamanikandan", "T"),
        ("Karthik", "P"),
        ("Karthik", "S"),
        ("Maharajothi", "T"),
        ("Meenatchi", "T"))

      // Higher order function
      val nameList = list.map(n => getName(firstName = n._1, lastName = n._2))

      println("Result: " + nameList)

    }

  def getName(firstName: String, lastName: String): String = firstName + "." + lastName

}


Here the map function takes a getName function as a parameter. This is called HOF (Higher order function).

Output:

Image title


How do you break a Monolith into Microservices at Scale? This ebook shows strategies and techniques for building scalable and resilient microservices.

Topics:
scala

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}