Scala Tutorial - Learn How To Create Partial Function Using the PartialFunction Trait

By Nadim Bahadoor | Last updated: March 16, 2018 at 11:39 am

Overview

In this tutorial, we will learn how to create Partial Function using the PartialFunction trait.

 

With pattern matching, if you recall from the Pattern Matching tutorial, you provide a series of case blocks. However, a Partial Function provides some but not all the possible case blocks.

 

If none of these make any sense, don't worry :) let's proceed with the examples below.

Steps

1. Review of Pattern Matching in Scala

First let's review Pattern Matching in Scala which you should already be familiar with from the Pattern Matching tutorial.

 

In the example below, you create a donut of type String with value Glazed Donut and then uses pattern matching to provide the cases for the different taste level.


println("Step 1: Review of Pattern Matching in Scala")
val donut = "Glazed Donut"
val tasteLevel = donut match {
  case "Glazed Donut" | "Strawberry Donut" => "Very tasty"
  case "Plain Donut" => "Tasty"
  case _ => "Tasty"
}
println(s"Taste level of $donut = $tasteLevel")

You should see the following output when you run your Scala application in IntelliJ:


Step 1: Review of Pattern Matching in Scala
Taste level of Glazed Donut = Very tasty

 

2. How to define a Partial Function named isVeryTasty

Instead of doing a full pattern match for the different taste level of a given donut, let's create a partial function named isVeryTasty which will only provide the case for very tasty donuts.


println("\nStep 2: How to define a Partial Function named isVeryTasty")
val isVeryTasty: PartialFunction[String, String] = {
  case "Glazed Donut" | "Strawberry Donut" => "Very Tasty"
}

NOTE:

  • Note that we are using the PartialFunction trait
  • In this example isVeryTasty takes an input of type String which is the donut and produces a String for the taste level. This is specified by PartialFunction[String, String]

3. How to call the Partial Function named isVeryTasty

Calling the partial function isVeryTasty from step 2 is no different than calling any other function - you simply need to pass its required parameter.


println("\nStep 3: How to call the Partial Function named isVeryTasty")
println(s"Calling partial function isVeryTasty = ${isVeryTasty("Glazed Donut")}")

You should see the following output when you run your Scala application in IntelliJ:


Step 3: How to call the Partial Function named isVeryTasty
Calling partial function isVeryTasty = Very Tasty

NOTE:

  • You will get scala.MatchError if the partial function does not have a case which matches the provided input.

4. How to define PartialFunction named isTasty and unknownTaste

Now that you know how to define partial functions as shown in Step 2 above, let's define two additional partial functions namely isTasty and unknownTaste.


println("\nStep 4: How to define PartialFunction named isTasty and unknownTaste")
val isTasty: PartialFunction[String, String] = {
  case "Plain Donut" => "Tasty"
}

val unknownTaste: PartialFunction[String, String] = {
  case donut @ _ => s"Unknown taste for donut = $donut"
}

 

5. How to compose PartialFunction using orElse

Functions in Scala are first class citizens and as such you can compose them. Let's go ahead and use the orElse() function which is inherited from the PartialFunction trait and create another PartialFunction named donutTaste.


println("\nStep 5: How to compose PartialFunction using orElse")
val donutTaste = isVeryTasty orElse isTasty orElse unknownTaste
println(donutTaste("Glazed Donut"))
println(donutTaste("Plain Donut"))
println(donutTaste("Chocolate Donut"))

You should see the following output when you run your Scala application in IntelliJ:


Step 5: How to compose PartialFunction using orElse
Very Tasty
Tasty
Unknown taste for donut = Chocolate Donut

This concludes our tutorial on Learn How To Create Partial Function Using the PartialFunction Trait and I hope you've found it useful!

 

Stay in touch via Facebook and Twitter for upcoming tutorials!

 

Don't forget to like and share this page :)

Summary

In this tutorial, we went over the following:

  • Review of Pattern Matching in Scala
  • How to define a Partial Function
  • How to call a Partial Function
  • How to compose Partial Function

Tip

Source Code

The source code is available on the allaboutscala GitHub repository.

 

What's Next

In the next tutorial, I will show you how to create Nested Functions.

Nadim Bahadoor on FacebookNadim Bahadoor on GithubNadim Bahadoor on LinkedinNadim Bahadoor on Twitter
Nadim Bahadoor
Technology and Finance Consultant with over 14 years of hands-on experience building large scale systems in the Financial (Electronic Trading Platforms), Risk, Insurance and Life Science sectors. I am self-driven and passionate about Finance, Distributed Systems, Functional Programming, Big Data, Semantic Data (Graph) and Machine Learning.
Other allaboutscala.com tutorials you may like: