Skip to main content
  1. Posts/

Scala Partially Applied Functions

·2 mins

Unless you’re completely new to Scala, you might have heard of partially applied functions, but maybe not known what to they’re useful for. They are useful for a lot of things, but there’s one use-case that I find particularly interesting.

Let’s say you want to generate HTML output from Scala, but you want to save yourself some time typing out opening and closing tags.

Let’s examine how this might look without partially applied functions:

def wrap(prefix: String, html: String, suffix: String) =
  prefix + html + suffix

To use this, we’d need to call it like so:

wrap("<div>", "Hello, world", "</div>")
//> "<div>Hello, world</div>"

Instead, we can save on typing and avoid mis-typing the div tags by defining a partially-applied function without multiple parameter groups:

val div = wrap("<div>", _: String, "</div>")

Now we can call div like this:

div("Hello, world")
//> "<div>Hello, world</div>"

You can probably imagine expanding on this. If we have these functions:

val html = wrap("<html>", _: String, "</html>")
val body = wrap("<body>", _: String, "</body>")
val div  = wrap("<div>", _: String, "</div>")
val h1   = wrap("<h1>", _: String, "</h1>")
val p    = wrap("<p>", _: String, "</p>")

We can then perhaps create these functions:

val docHeader = h1
val docBody   = div compose p
val doc       = html compose body

And then create a template function:

val template: String => String => String =
  _header =>
    _body =>
      doc(
        docHeader(_header) +
          docBody(_body),
      )

Then we can call it:

template("Header 1")("Hello, world")
//> "<html><body><h1>Header 1</h1><div><p>Hello, world</p></div></body></html>"