home search about rss feed twitter ko-fi

Functions: Passing Functions Into HOFs (Scala 3 Video)

A higher-order function (HOF) is a function that takes another function as an input parameter. (An HOF can also return a function as a result, and we’ll discuss that feature in the Advanced Scala 3 course.)

Scala examples of HOFs with anonymous functions

Here are Scala HOF examples of foreach, filter, and map taking anonymous functions as input parameters:

val strings = List("jyn", "cassian", "bodhi")

// foreach
strings.foreach(s => println(s.length))

// filter
val a = strings.filter(_.length < 4)

// map
val capNames = strings.map(_.toUpperCase)

Examples of Scala HOFs with regular named functions

To get started, here’s a Scala function that returns true if the Int it’s given is an even number, or false otherwise:

def isEven(i: Int): Boolean =
    i % 2 == 0

These examples show how isEven works:

isEven(1)   // false
isEven(2)   // true

A great thing about HOFs is that not only can they take anonymous functions, but they also take regular functions like isEven:

val ints = List(1, 2, 3, 4, 5)
ints.filter(isEven)    // ints: List(2, 4)

This example works because:

  • ints is a List[Int] (a list of integers)
  • filter passes one element at a time to your function
  • filter is an HOF that takes your function as an input parameter, and your function must:
    • take an Int as input
    • and return a Boolean

Because isEven matches that description — it takes an Int input parameter and returns a Boolean — it can be used with filter.

A map example

Similarly, this is a function that returns a truncated version of the string it’s given, so that it’s no more than two characters in length:

def truncate(s: String): String = s.take(2)

Because truncate takes a String input parameter, it can be used with map on a List[String]:

val a = List("jyn", "cassian", "bodhi")

val b = a.map(truncate)   // b: List("jy", "ca", "bo")

Once again this works because:

  • map passes one element at a time to your function
  • In this case map is being called on a List[String], so each element it passes has the type String
  • The truncate function takes a single String as its input parameter

Note that map can be called in all of these equivalent ways:

val b = a.map(s => truncate(s, 3))
val b = a.map(truncate)
val b = a.map(truncate(_, 3)) 

Update: All of my new videos are now on
LearnScala.dev