Learn How To Create Function With Parameters

By Nadim Bahadoor | Last updated: July 25, 2017 at 13:42 pm

Overview

In this tutorial, we will learn how to create functions that take parameters as input in Scala. In addition, we will also see how you can assign default values to the parameters.

 

If you are unfamiliar with the syntax for defining functions, please review the previous tutorial on creating and using functions in Scala.

Steps

1. How to define function with parameters

To define a function with parameters, you need to enclose your input parameters within the parenthesis (). Suppose you would like to define a function called calculateDonutCost which will have the following parameters: donutName of type String and quantity of type Int.


println("Step 1: How to define function with parameters")
def calculateDonutCost(donutName: String, quantity: Int): Double = {
  println(s"Calculating cost for $donutName, quantity = $quantity")

  // make some calculations ...
  2.50 * quantity
}

NOTE:

  • Inside the body of our calculateDonutCost function, we are simply multiplying the quantity parameter by a hard coded price value of 2.50.
  • Notice that we explicitly added the return type of : Double = {...} to the function. Although we could have leveraged the type inference feature of Scala, it is a good practice to be explicit about the return types of your function.

2. How to call a function with parameters

To call the calculateDonutCost function which you've defined in Step 1, you simply need to call the function by its name, open parenthesis,  then fill in the blanks for the corresponding input parameters and then close parenthesis.

As an example, let's call our calculateDonutCost function with Glazed Donut as the first parameter of type String and then the number 5 as its second parameter of type Int.


println("\nStep 2: How to call a function with parameters")
val totalCost = calculateDonutCost("Glazed Donut", 5)
println(s"Total cost of donuts = $totalCost")

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


Step 2: How to call a function with parameters
Calculating cost for Glazed Donut, quantity = 5
Total cost of donuts = 12.5

NOTE:

  • We've stored the value which is returned from our calculateDonutCost function into an immutable variable called totalCost.
  • Notice also that we are using Scala's type inference with the totalCost variable and as such did not explicitly specified its type of Double. In large code-base however, be wise about being explicit for your data points where necessary.

3. How to add default values to function parameters

What if some customers who present you a coupon code are eligible for additional discount when buying donuts from your store? Let's add another parameter named couponCode of type String. But, since not all customers will have a coupon code, let's default the value of couponCode to say "NO CODE".


println("\nStep 3: How to add default values to function parameters")
def calculateDonutCost(donutName: String, quantity: Int, couponCode: String = "NO CODE"): Double = {
  println(s"Calculating cost for $donutName, quantity = $quantity, couponCode = $couponCode")
// make some calculations ...
2.50 * quantity
}

NOTE:

  • Limit your use of defaulting parameters for simple cases only.
  • There are better ways to achieve the desired effect of some customers presenting a coupon code such as using Option which we will see in the next tutorial.

4. How to call a function with parameters that has default values

Since coupon code parameter is defined with a default value as shown in Step 3, you can then call calculateDonutCost function by either adding some coupon code or not!


println("\nStep 4: How to call a function with parameters that has default values")
val totalCostWithDiscount = calculateDonutCost("Glazed Donut", 4, "COUPON_12345")
val totalCostWithoutDiscount = calculateDonutCost("Glazed Donut", 4)

NOTE:

  • If you were using Java, you would have had to use method overloading to achieve the same desired effect.
  • However, the ability to provide a default value to function parameters in Scala is a much more elegant solution!

This concludes our tutorial on Learn How To Create Function With 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 define function with parameters
  • How to call a function with parameters
  • How to add default values to function parameters
  • How to call a function with parameters that has default values

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 make use of the Option type to be explicit about function parameters that are optional.

Nadim Bahadoor on FacebookNadim Bahadoor on GithubNadim Bahadoor on LinkedinNadim Bahadoor on Twitter
Nadim Bahadoor
Senior Software Developer | Nephila Capital
Founder of allaboutscala.com. I have over 10 years of experience in building large scale real-time trading systems in the financial industry. Passionate about Distributed Systems, Scala, Big Data and Functional Programming. Stay in touch for upcoming tutorials!
Other allaboutscala.com tutorials you may like:

Share this article on