Learn How To Use Option In Function Parameters

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

Overview

In this tutorial, we will learn how to use the Option type to define and use functions which take optional parameters.

 

Feel free to review the tutorial from Chapter 2 on how to use Option, Some and None to help avoid the dreaded NullPointerException.

Steps

1. How to define an Option in a function parameter

Let's redo the example from the previous tutorial on Learn How To Create Function Parameters where we had provided a default value to the couponCode parameter.

 

To recap, our use case is that not all our customers who are buying donuts from our store would have a coupon code. Hence, the coupon code parameter should be optional.

 

In Scala, this means that you can declare couponCode using the Option type. Since our coupon code will be a String, couponCode parameter should be declared as: couponCode: Option[String]


println("Step 1: How to define an Option in a function parameter")
def calculateDonutCost(donutName: String, quantity: Int, couponCode: Option[String]): Double = {
  println(s"Calculating cost for $donutName, quantity = $quantity")

  couponCode match {
    case Some(coupon) =>
    val discount = 0.1 // Let's simulate a 10% discount
    val totalCost = 2.50 * quantity * (1 - discount)
    totalCost

    case None => 2.50 * quantity
  }
}

NOTE:

  • Inside our function, we will test for a valid couponCode using pattern matching.
  • In the case of Some(coupon), we assume a database lookup for the discount that needs to be applied. But, in our example, we will assume the discount is 10%.
  • As part of the pattern matching, we also provide the None case where no couponCode was passed-through.

2. How to call a function which has an Option parameter

Let's use the function defined in Step 1 to calculate the cost for a customer buying 5 Glazed Donuts:


println("\nStep 2: How to call a function which has an Option parameter")
println(s"""Total cost = ${calculateDonutCost("Glazed Donut", 5, None)}""")

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


Step 2: How to call a function which has an Option parameter
Calculating cost for Glazed Donut, quantity = 5
Total cost = 12.5

NOTE:

  • Since our customer does not have a couponCode, we had to supply a None as the couponCode parameter.
  • Providing a None for every Option parameter is perhaps not very elegant. Fortunately, this is easily solved - see Step 3 below.

3. How to assign a default value to an Option parameter

To assign a default value of None as part of the declaration for couponCode parameter, you can use the following syntax:


println("\nStep 3: How to assign a default value to an Option parameter")
def calculateDonutCostWithDefaultOptionValue(donutName: String, quantity: Int, couponCode: Option[String] = None): Double = {
  println(s"Calculating cost for $donutName, quantity = $quantity")

  couponCode match{
    case Some(coupon) =>
      val discount = 0.1 // Let's simulate a 10% discount
      val totalCost = 2.50 * quantity * (1 - discount)
      totalCost

    case _ => 2.50 * quantity
  }
}

 

4. How to call a function whose Option parameter has a default value

Using the function defined in Step 3, you no longer have to pass-through a None value for the Option couponCode parameter.

 

If you have a legitimate couponCode to pass-through, you can use Some() as shown below:


println(\n"Step 4: How to call a function which has an Option parameter with a default value")
println(s"""Total cost = ${calculateDonutCostWithDefaultOptionValue("Glazed Donut", 5)}""")
println(s"""Total cost with discount = ${calculateDonutCostWithDefaultOptionValue("Glazed Donut", 5, Some("COUPON_1234"))}""")

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


Step 4: How to call a function which has an Option parameter with a default value
Calculating cost for Glazed Donut, quantity = 5
Total cost = 12.5
Calculating cost for Glazed Donut, quantity = 5
Total cost with discount = 11.25

This concludes our tutorial on Learn How To Use Option In Function Parameters 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:

  • How to use an Option as part of a function parameter
  • How to provide a default value of None an Option parameter
  • How to pass Some() to an Option parameter when calling the function

Tip

  • How to use the map function to extract a valid Option value
println(s"\nTip 1: Use the map function to extract a valid Option value")
val favoriteDonut: Option[String] = Some("Glazed Donut")
favoriteDonut.map(d => println(s"Favorite donut = $d"))

val leastFavoriteDonut: Option[String] = None
leastFavoriteDonut.map(d => println(s"Least Favorite donut = $d"))

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 define a function whose return type is an Option.

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: